thymeleaf 局部变量
局部变量只在局部片段内有效,可使用 th:with 自定义一个局部变量
**********************
示例
***************
pojo 层
Person
@Data
public class Person {
private Integer id;
private String name;
private Integer age;
}
***************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public ModelAndView hello(ModelAndView mv){
Person person=new Person();
person.setId(1);
person.setName("瓜田李下");
person.setAge(20);
mv.addObject("person",person);
mv.setViewName("test");
return mv;
}
}
***************
前端页面
test.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:align="center" style="color: coral" th:object="${person}">
<strong>
<span th:text="*{id}"></span> ==>
<span th:text="*{name}"></span> ==>
<span th:text="*{age}"></span>
</strong>
</div><br>
<div th:align="center" style="color: purple" th:with="per=${person}">
<strong>
<span th:text="${per.id}"></span> ==>
<span th:text="${per.name}"></span> ==>
<span th:text="${per.age}"></span>
</strong>
</div>
</body>
</html>
**********************
使用测试
localhost:8080/hello