1. 引言
Thymeleaf 是 SpringBoot 官方推荐的模板引擎,语法简洁、与 HTML 完美融合,非常适合快速开发服务端渲染页面。本文用最少的篇幅带你跑通一个 Thymeleaf 示例。
2. 引入依赖
在 pom.xml 中添加:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3. 目录结构
模板文件默认放在 src/main/resources/templates/ 下,静态资源放在 static/ 下。
src/main/resources/
├── static/
└── templates/
└── index.html
4. 编写控制器
java
@Controller
public class HelloController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "SpringBoot");
return "index";
}
}
5. 编写模板
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name}">Hello</h1>
</body>
</html>
6. 常用语法
- 取值 :
th:text="${name}" - 条件 :
th:if="${condition}" - 循环 :
th:each="item : ${list}" - 链接 :
th:href="@{/path}"
7. 用法总结
7.1 标准表达式
- 变量表达式 :
${name},等价于model.addAttribute("name", ...)中的取值。 - 选择表达式 :
*{field},配合th:object使用,直接取当前对象的属性。 - 链接表达式 :
@{/path},自动拼接上下文路径,支持参数如@{/user/{id}(id=${user.id})}。 - 消息表达式 :
#{msg},读取国际化资源文件中的文案。
7.2 常用属性
| 属性 | 作用 | 示例 |
|---|---|---|
th:text |
输出文本 | th:text="${name}" |
th:if |
条件判断 | th:if="${user != null}" |
th:unless |
条件取反 | th:unless="${user.admin}" |
th:each |
循环遍历 | th:each="item : ${list}" |
th:href |
生成链接 | th:href="@{/detail/{id}(id=${item.id})}" |
th:src |
图片地址 | th:src="@{/img/logo.png}" |
th:class |
动态样式 | th:class="${active ? 'on' : 'off'}" |
th:object |
绑定对象 | th:object="${user}" |
7.3 内联写法
不想写标签属性时,可用 [[${name}]] 直接输出变量,适合在 <script> 或文本中混用。
7.4 片段复用
用 th:fragment 定义公共片段,用 th:replace 或 th:insert 引入,实现页面组件化复用。
7.5 小结
掌握表达式、常用属性、内联与片段复用这四块,就能覆盖绝大多数 Thymeleaf 开发场景。配合 SpringBoot 的自动配置,无需额外 XML 配置即可开箱即用。