Thymeleaf类似其他编程语言,也有变量的概念,在我们在前后端进行交互时,通过变量可以使我们很好地进行信息传递,
全局变量
一般我们在前后端进行交互时,可以通过 org.springframework.ui.Model 和 HttpServletRequest 来进行参数传递与赋值,如下所示
package com.caigentan.thymeleaf;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
//注意:@Controller注解的类需要放在 SpringBasicApplication.java 同级或者下层才有作用,否则会 404
@Controller
public class VariableProgram {
@GetMapping("/variable")
public String ariableProgram(Model model, HttpServletRequest request) {
model.addAttribute("variable1", "变量1");
request.setAttribute("variable2", "变量2");
return "variable";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:utext="${variable1}"></p>
<p th:utext="${variable2}"></p>
</body>
</html>
结果:
局部变量
package com.caigentan.spring.thymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LocalVariableProgram {
@RequestMapping("localVar")
public String localVariable(Model model) {
String[] countries = new String[]{"中国", "越南", "古巴", "朝鲜"};
model.addAttribute("countries", countries);
return "localvariable";
}
}
localvariable.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<th>No</th>
<th>Name</th>
</tr>
<tr th:each="country,iter:${countries}">
<td th:utext="${iter.count}"></td>
<td th:utext="${country}"></td>
</tr>
</table>
</body>
</html>
效果:
当然我们也可以使用Thymeleaf进行参数赋值(th:with),以构成自定义局部变量,如下所表示,在localvariable.html中新添:
<div th:with="country0=${countries[0]}">
<h2>th:with</h2>
<p th:utext="${country0}"></p>
</div>
运行效果如下:
注:th:with的赋值不可跨域
其他的变量叙述请查阅