以下是thymeleaf 常用写法:
- 控制器端变量渲染到模板写法
控制器方法需要一个ModelMap来传递变量
@Controller
public class Hello {
@GetMapping(value="/hello")
public String index(ModelMap map){
map.addAttribute("msg","this is a message");
return "hello";
}
}
模板写法
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>hello</h1>
<h4 th:text="${msg}">msg</h4>
</body>
</html>
- 条件判断写法:
<span th:if="${show} ">显示此信息</span>
-多条件可以用switch
<div th:switch="${show}">
<p th:case="1">这是第一条消息</p>
<p th:case="2">这是第二条消息</p>
</div>
- 遍历数组:
控制器端代码:
@Controller
public class Hello {
@GetMapping(value="/hello")
public String index(ModelMap map){
List<User> userList=new ArrayList<User>();
userList.add(new User("Tom",1l,1));
userList.add(new User("Jack",2l,21));
userList.add(new User("Rose",3l,11));
userList.add(new User("Nock",4l,18));
map.addAttribute("users",userList);
return "hello";
}
}
User实体类
public class User {
private Long id;
private String name;
private Integer age;
public User(String name,Long id,Integer age){
this.name=name;
this.age=age;
this.id=id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString(){
return "name="+getName()+" age="+getAge()+" id="+getId();
}
}
模板中把用户数据遍历出来写在一个表格里
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>hello</h1>
<table>
<tr th:each="user : ${users}">
<td th:text="${user.name}">tyrone</td>
<td th:text="${user.age}">18</td>
<td th:text="${user.id}">18</td>
</tr>
</table>
</body>
</html>
-设置任意自定义属性
<span th:goods_id="${goods_id}">这是一个消息</span>
- 显示session中的内容
@Controller
public class Hello {
@GetMapping(value="/hello")
public String index(HttpSession session){
session.setAttribute("msg","这是一个sesson消息");
return "hello";
}
}
模板
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>hello</h1>
<span th:text="${session.msg}">占个位</span>
</body>
</html>