配置
Spring Boot添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
模板配置
#thymeleaf模板配置 thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 #开发时关闭缓存,不然没法看到实时页面 cache: false
html文件引入标签才能使用th:
xmlns:th="http://www.thymeleaf.org"
语法
标准表达式语法
-
简单表达式
-
变量表达式:
${...}
-
选择变量表达式:
*{...}
-
消息表达式:
#{...}
-
URL 表达式:
@{...}
-
代码段表达式:
~{...}
-
比较
Thymeleaf支持比较操作符>(gt)
, <(lt)
, >=(ge)
, <=(le)
, ==(eq)
, !=(neq/ne)
, !(not)
th:if="${prodStat.count} > 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
由于“>
”和“<
”在XML里面有特殊的意义,不能在属性值里使用,但是可以用“>
“和”<
“代替
条件
-
if/unless th:if是该标签在满足条件的时候才会显示,unless是不成立时候才显示,例如
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
-
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 some other thing</p> </div>
循环
List循环
<tr th:each="service:${services}" > <td th:text="${serviceStat.index+1}"></td> <td th:text="${service.name}"></td> <td th:text="${service.address}