Thymeleaf的常用用法
1.赋值,拼接
@GetMapping("/index2")
public String index2(Map<String,String> map){
map.put("name","张三");
return "index2";
}
<p th:text="${name}"></p>
<p th:text="学生姓名+${name}+你好"></p>
<p th:text="|学生姓名,${name}|"></p>
2.条件判断: if/unless
th:if 表示条件成立时显示内容,th:unless 表示条件不成立时显示内容
@GetMapping("/if")
public String index3(Map<String,Boolean> map){
map.put("flag",true);
return "index";
}
<p th:if="${flag==true}" th:text="if判断成立"></p>
<p th:unless="${flag==true}" th:text="unless判断成立"></p>
3.循环
循环用的比较多
stat 是状态变量,属性:
1.index集合中元素的 index (从0开始)
2.count集合中元素的 count (从1开始)
3.size 集合的大小
4.current当前迭代变量
5.even/odd当前迭代是否为奇数/偶数(从0开始)
6.first当前迭代元素是否为第一个
7.last当前迭代元素是否为最后一个
@GetMapping("/index")
public String index(Model model){
System.out.println("index....");
List<Student> list=new ArrayList<>();
list.add(new Student(1L,"幸福哈",22));
list.add(new Student(2L,"张三",23));
list.add(new Student(3L,"李四",24));
model.addAttribute("list",list);
return "/index";
}
<table>
<tr>
<td>index</td>
<td>count</td>
<td>学生ID</td>
<td>学生姓名</td>
<td>学生年龄</td>
</tr>
<tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'red'}">
<td th:text="${stat.index}"></td>
<td th:text="${stat.count}"></td>
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
</tr>
</table>