(1) 在pom.xml中引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2) 关闭thymeleaf缓存,只在开发时关闭
在application.properties配置
spring.thymeleaf.cache=false
(3) 前端html页面标签中引入如下:
<html xmlns:th="http://www.thymeleaf.org">
(4)在需要的标签里使用th:*
(5)获取变量值
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
$符号获取变量值。name 是controller层里model.addAttribute保存的键。th:text
标签的值替换p
标签里面的值,3333会被覆盖
循环关键词:th:each
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
条件判断,关键词th:if/unless
标签里加入 th:unless,表示:条件不通过时才会显示此标签.例<p th:unless="${name != null}">123</p>
标签里加入 th:if,表示:条件通过时才会显示此标签
Switch
Thymeleaf同样支持多路选择Switch结构:default可以用 * 表示
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is a manager</p>
</div>
Utilities
为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问
注释 <!--/* 注释 */-->
选择表达式
*表达式
<div th:object="${user}">
<p th:text="*{password}"></p>
</div>
th:object="${user}"是获取controller层里model.addAttribute所保存的键,如model.addAttribute("user",user);
th:text="*{password}" 是获取user实体类里字段的值
修改时间格式
<p th:text="${#dates.format(users.datetime,'yyyy-MM-dd')}"></p>
users是循环体的别名,datetime是字段名
下拉框
<select name="subId">
<option value="">请选择</option>
<option th:each="channelsub:${subchannels}"
th:selected="${channelsub.id == subId}"
th:value="${channelsub.id}"
th:text="${channelsub.name}"></option>
</select>