Thymeleaf 核心语法笔记

一、基础配置

  • 命名空间声明:在 HTML 根标签中添加 Thymeleaf 命名空间,启用语法支持:
1
<html lang="en" xmlns:th="http://www.thymeleaf.org">

二、核心语法分类及示例

1. 动态属性渲染(th:xxx

通过 th:属性名 动态设置 HTML 标签的属性值或执行指令,支持所有 HTML 属性及 Thymeleaf 自定义指令。

语法 作用 示例
th:text 动态渲染标签体内的文本 <span th:text="${username}"></span>(显示 Model 中的 username
th:属性名 动态设置标签的指定属性(如 idsrc <span th:id="${username}"></span>(用 username 作为 id 属性值)
th:attr 动态设置任意属性(适用于自定义属性) <div th:attr="data-id=${user.id}"></div>
指令类(th:if/th:each 条件判断 / 循环遍历 见下文详细说明

2. 取值表达式

用于从 Model 或上下文获取数据,常用表达式如下:

表达式 作用 示例
${} 变量取值(获取 Model 中的数据) ${username}(获取用户名)
@{} URL 路径生成(自动拼接上下文路径) <a th:href="@{/login}">登录</a>
#{} 国际化消息取值(从配置文件读取多语言) #{message.login.success}
~{} 片段引用(复用页面片段) th:insert="~{common/header :: header}"
*{} 变量选择(简化对象属性访问) 配合 th:object 使用,如 *{name}

3. 循环遍历(th:each

用于遍历 Model 中的集合数据(如列表),语法:

th:each="元素变量名, 状态变量 : ${集合}"

  • 示例
1
2
3
4
5
<!-- 遍历 users 集合,每次循环的元素为 user -->
<tr th:each="user : ${users}">
<td>[[${user.id}]]</td> <!-- 行内写法显示 id -->
<td th:text="${user.username}"></td> <!-- 显示用户名 -->
</tr>
  • 状态变量(可选,常用属性):

    • stat.index:从 0 开始的索引
    • stat.count:从 1 开始的计数
    • stat.odd/stat.even:是否为奇数 / 偶数行
    • stat.first/stat.last:是否为第一 / 最后一个元素

4. 条件判断(th:if

根据表达式结果(布尔值)决定是否渲染当前标签,语法:

th:if="${条件表达式}"

  • 示例

    1
    2
    3
    4
    <!-- 年龄 >=18 显示“成年”,否则不显示 -->
    <td th:if="${user.age >= 18}">成年</td>
    <!-- 搭配 th:unless 使用(等价于 !条件) -->
    <td th:unless="${user.age >= 18}">未成年</td>
  • 简化写法:用三元运算符在 th:text 中直接判断:

1
<td th:text="${user.age >= 18 ? '成年' : '未成年'}"></td>

5. 行内写法([[ ]]

在 HTML 文本中直接嵌入取值表达式,等价于 th:text,更简洁:

  • 示例
1
2
<h2>密码:[[${password}]]</h2>
<!-- 等价于 <h2>密码:<span th:text="${password}"></span></h2> -->

三、核心特点

  • 自然模板:模板文件本身是合法的 HTML,未渲染时可直接在浏览器打开。
  • 动态渲染:通过 th:xxx 指令将 Model 中的数据动态填充到页面。
  • 功能全面:支持变量取值、循环、判断、URL 处理、国际化等常见需求。

四、示例代码解析(结合提供的 HTML)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 1. 命名空间声明 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<!-- 2. th:text 渲染文本,th:id 动态设置id -->
<h2>用户名:<span th:text="${username}" th:id="${username}"></span></h2>

<!-- 3. 行内写法 [[ ]] 显示密码 -->
<h2>密码:[[${password}]]</h2>

<!-- 4. th:each 遍历 users 集合 -->
<tr th:each="user : ${users}">
<td>[[${user.id}]]</td> <!-- 行内写法显示id -->
<td th:text="${user.getUsername()}"></td> <!-- 调用对象方法取值(不推荐,建议用 ${user.username}) -->
<td th:text="${user.age}"></td> <!-- 直接访问属性 -->
<td th:text="${user.age >= 18 ? '成年' : '未成年'}"></td> <!-- 三元运算符判断 -->
</tr>