一、Thymeleaf 核心语法
1. 变量表达式(Variable Expressions)
• 语法:${...}
• 作用:访问模型(Model)中的属性或执行表达式。
• 示例:
<!-- 输出用户名称 -->
<div th:text="${user.name}">默认名称</div>
<!-- 支持链式调用 -->
<div th:text="${user.address?.city}">默认城市</div>
2. 链接表达式(Link Expressions)
• 语法:@{...}
• 作用:生成 URL,支持路径参数和查询参数。
• 示例:
<!-- 绝对路径 -->
<a th:href="@{https://example.com}">外部链接</a>
<!-- 带路径参数 -->
<a th:href="@{/user/{id}/profile(id=${userId})}">用户资料</a>
<!-- 带查询参数 -->
<a th:href="@{/search(page=1,keyword=${keyword})}">搜索</a>
3. 消息表达式(Message Expressions)
• 语法:#{...}
• 作用:国际化消息(从 messages.properties
读取)。
• 示例:
<!-- messages.properties 中定义:welcome.message=Welcome! -->
<h1 th:text="#{welcome.message}">默认欢迎语</h1>
4. 选择表达式(Selection Expressions)
• 语法:*{...}
• 作用:绑定表单对象,需配合 th:object
使用。
• 示例:
<form th:object="${user}">
<input type="text" th:field="*{name}" />
<input type="email" th:field="*{email}" />
</form>
5. 条件判断(Conditional Logic)
• 语法:th:if
、th:unless
、th:switch
• 示例:
<!-- 简单条件 -->
<div th:if="${user.isAdmin}">管理员面板</div>
<div th:unless="${user.isAdmin}">普通用户</div>
<!-- 多条件判断 -->
<div th:switch="${user.role}">
<p th:case="'admin'">管理员</p>
<p th:case="'user'">普通用户</p>
<p th:case="*">未知角色</p>
</div>
6. 循环遍历(Iteration)
• 语法:th:each
• 示例:
<ul>
<li th:each="item : ${items}" th:text="${item.name}">默认项</li>
</ul>
<!-- 循环状态变量 -->
<table>
<tr th:each="user, stat : ${users}">
<td th:text="${stat.index}">序号</td>
<td th:text="${user.name}">用户名</td>
<td th:text="${stat.size}">总数量</td>
</tr>
</table>
7. 表单处理(Form Handling)
• 语法:th:action
、th:field
、th:errors
• 示例:
<!-- 表单绑定 -->
<form th:action="@{/save}" th:object="${user}" method="post">
<input type="text" th:field="*{name}" />
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div>
<button type="submit">提交</button>
</form>
8. 模板布局(Template Layout)
• 语法:th:fragment
、th:insert
、th:replace
• 示例:
<!-- 定义片段(header.html) -->
<header th:fragment="commonHeader">
<h1>公共头部</h1>
</header>
<!-- 插入片段 -->
<div th:insert="~{header :: commonHeader}"></div>
<!-- 替换片段 -->
<div th:replace="~{header :: commonHeader}"></div>
9. 内联语法(Inline Syntax)
• 语法:[[...]]
(转义)、[(...)]
(不转义)
• 示例:
<!-- 转义输出 -->
<span>用户名:[[${user.name}]]</span>
<!-- 不转义输出(谨慎使用) -->
<div>[(${rawHtmlContent})]</div>
10. URL 和静态资源处理
• 语法:th:href
、th:src
• 示例:
<!-- 静态资源路径 -->
<link th:href="@{/css/style.css}" rel="stylesheet">
<script th:src="@{/js/app.js}"></script>
<img th:src="@{/images/logo.png}" alt="Logo">
二、Thymeleaf 工具类函数
1. 常用工具对象
• 字符串处理:#strings
<div th:text="${#strings.toUpperCase(user.name)}"></div>
<div th:text="${#strings.substring(user.email, 0, 5)}"></div>
• 日期处理:#dates
<div th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"></div>
• 集合处理:#lists
、#arrays
<div th:if="${#lists.isEmpty(items)}">列表为空</div>
2. Spring 集成功能
• 调用 Spring Bean:
<div th:text="${@myService.getData()}"></div>
• Spring Security 集成:
<div sec:authorize="hasRole('ADMIN')">仅管理员可见</div>
三、Thymeleaf 配置详解
1. 关键配置项(application.properties
)
# 模板路径前缀
spring.thymeleaf.prefix=classpath:/templates/
# 模板后缀
spring.thymeleaf.suffix=.html
# 模板模式(HTML5)
spring.thymeleaf.mode=HTML5
# 是否启用缓存(开发时建议关闭)
spring.thymeleaf.cache=false
# 模板编码
spring.thymeleaf.encoding=UTF-8
2. 开发环境调试技巧
• 实时刷新模板:设置 spring.thymeleaf.cache=false
。
• 错误信息定位:Thymeleaf 会直接输出模板中的错误行号。
四、注意事项
- XSS 防护:优先使用
th:text
或[[...]]
自动转义内容,避免直接使用th:utext
。 - 性能优化:生产环境开启缓存(
spring.thymeleaf.cache=true
)。 - 模板组织:使用
th:fragment
和th:replace
提高代码复用性。 - 逻辑简化:避免在模板中编写复杂业务逻辑,保持模板简洁。
五、完整示例
1. Controller 代码
@Controller
public class UserController {
@GetMapping("/user/{id}")
public String userProfile(@PathVariable Long id, Model model) {
User user = userService.findById(id);
model.addAttribute("user", user);
return "user/profile";
}
}
2. 模板文件(profile.html
)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${user.name} + '的资料'">用户资料</title>
<link th:href="@{/css/profile.css}" rel="stylesheet">
</head>
<body>
<div th:replace="~{common/header :: header}"></div>
<h1 th:text="'欢迎 ' + ${user.name}">欢迎用户</h1>
<div th:if="${user.isActive}">用户已激活</div>
<ul>
<li th:each="order : ${user.orders}" th:text="${order.id}"></li>
</ul>
</body>
</html>
通过以上内容,可以全面掌握 Thymeleaf 在 Spring Boot 中的语法和使用场景。