Thymeleaf 语法

一、基础准备
  1. 引入 Thymeleaf 在 HTML 页面的 <html> 标签中添加命名空间,让 IDE 识别 Thymeleaf 语法并提供提示:

    复制代码
    <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
  2. 核心依赖(Maven) 若使用 Spring Boot,只需引入 starter 依赖即可:

    xml

    复制代码
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
二、核心语法分类
1. 变量表达式(${})
  • 作用:获取后端传递到页面的变量值,是最常用的语法。

  • 语法th:text="${变量名}"

  • 示例 :后端(Controller):

    复制代码
    @GetMapping("/user")
    public String getUser(Model model) {
        User user = new User("张三", 20);
        model.addAttribute("user", user);
        model.addAttribute("msg", "欢迎使用Thymeleaf");
        return "user";
    }

    前端页面:

    html

    预览

    复制代码
    <!-- 直接输出普通变量 -->
    <div th:text="${msg}">默认显示内容</div>
    
    <!-- 输出对象属性(支持点语法/方括号语法) -->
    <div th:text="${user.name}">默认姓名</div>
    <div th:text="${user['age']}">默认年龄</div>
  • 说明th:text 会替换标签内的文本内容;若变量为 null,标签内默认内容会显示(开发时可用于占位)。

2. 选择变量表达式(*{})
  • 作用 :基于已选择的对象(th:object)简化属性访问,避免重复写对象名。

  • 语法 :先通过 th:object 指定对象,再用 *{} 访问属性。

  • 示例

    复制代码
    <div th:object="${user}">
        <p th:text="*{name}">姓名</p>
        <p th:text="*{age}">年龄</p>
    </div>
  • 等价写法*{name} 等价于 ${user.name},适合对象属性较多的场景。

3. 消息表达式(#{})
  • 作用 :读取国际化配置文件(.properties)中的文本,实现多语言。

  • 语法th:text="#{配置项key}"

  • 示例 :国际化文件(messages_zh_CN.properties):

    properties

    复制代码
    welcome=欢迎访问
    user.name=用户名

    页面使用:

    复制代码
    <div th:text="#{welcome}">默认欢迎语</div>
    <label th:text="#{user.name}">姓名</label>
4. 链接表达式(@{/})
  • 作用:生成绝对路径 / 相对路径,自动拼接上下文路径(避免硬编码)。

  • 语法

    • 无参数:th:href="@{/路径}"
    • 带参数:th:href="@{/路径(参数1=值1,参数2=值2)}"
  • 示例

    复制代码
    <!-- 普通链接 -->
    <a th:href="@{/home}">首页</a>
    
    <!-- 带参数链接 -->
    <a th:href="@{/user/detail(id=1,type=normal)}">用户详情</a>
    
    <!-- 静态资源(CSS/JS) -->
    <link th:href="@{/css/style.css}" rel="stylesheet">
    <script th:src="@{/js/index.js}"></script>
5. 片段表达式(~{})
  • 作用:复用页面片段(如页眉、页脚、侧边栏),减少代码冗余。
  • 核心标签
    • th:fragment:定义片段
    • th:insert/th:replace/th:include:引入片段(三者区别见下表)
标签 作用 特点
th:insert 插入片段到当前标签内 保留当前标签,片段作为子元素
th:replace 用片段替换当前标签 不保留当前标签,直接替换
th:include 插入片段的内容到当前标签 仅保留片段文本,已过时
  • 示例 :定义片段(fragments/header.html):

    复制代码
    <div th:fragment="header">
        <h1>网站头部</h1>
        <nav>导航栏</nav>
    </div>

    引入片段:

    复制代码
    <!-- 插入片段(保留当前div标签) -->
    <div th:insert="~{fragments/header :: header}"></div>
    
    <!-- 替换片段(当前div被片段替换) -->
    <div th:replace="~{fragments/header :: header}"></div>
    
    <!-- 简写(省略~{}) -->
    <div th:replace="fragments/header :: header"></div>
三、常用属性
1. 文本操作
属性 作用 示例
th:text 替换标签内文本(转义 HTML) <p th:text="${msg}">默认值</p>
th:utext 替换标签内文本(不转义 HTML) <p th:utext="${htmlMsg}">默认值</p>
2. 条件判断
  • th:if:条件为 true 时显示标签

  • th:unless:条件为 false 时显示标签(与 th:if 相反)

  • th:switch/th:case:多分支判断(类似 Java 的 switch)

  • 示例

    html

    预览

    复制代码
    <!-- 简单条件 -->
    <div th:if="${user.age >= 18}">成年</div>
    <div th:unless="${user.age >= 18}">未成年</div>
    
    <!-- 多分支 -->
    <div th:switch="${user.type}">
        <p th:case="1">普通用户</p>
        <p th:case="2">VIP用户</p>
        <p th:case="*">未知用户</p> <!-- 默认分支 -->
    </div>
3. 循环遍历
  • th:each :遍历集合(List/Map/ 数组),语法:th:each="元素, 状态变量 : ${集合}"

  • 状态变量常用属性

    • index:索引(从 0 开始)
    • count:计数(从 1 开始)
    • size:集合大小
    • even/odd:是否偶数 / 奇数行
    • first/last:是否第一个 / 最后一个元素
  • 示例

    复制代码
    <!-- 遍历List -->
    <ul>
        <li th:each="u, stat : ${userList}" 
            th:text="${u.name} + ' - ' + stat.count"
            th:class="${stat.odd} ? 'odd-row' : 'even-row'">
            默认内容
        </li>
    </ul>
    
    <!-- 遍历Map -->
    <div th:each="entry : ${map}">
        键:<span th:text="${entry.key}"></span>
        值:<span th:text="${entry.value}"></span>
    </div>
4. 动态属性
  • th:attr:设置任意 HTML 属性

  • 简写属性 (更常用):th:id/th:class/th:src/th:href/th:value

  • 示例

    复制代码
    <!-- 动态设置id和class -->
    <div th:id="'user-' + ${user.id}" th:class="${user.status} ? 'active' : 'disable'"></div>
    
    <!-- 动态设置输入框值 -->
    <input type="text" th:value="${user.name}">
    
    <!-- 动态设置checked -->
    <input type="checkbox" th:checked="${user.agree}">
5. 内联表达式
  • 作用:在 HTML 文本 / JS 中直接使用 Thymeleaf 表达式,无需标签属性。

  • 语法

    • 文本内联:[[${变量}]](转义 HTML)、[(${变量})](不转义 HTML)
    • JS 内联:在 <script> 标签中加 th:inline="javascript",然后用 /*[[${变量}]]*/
  • 示例

    复制代码
    <!-- 文本内联 -->
    <p>Hello, [[${user.name}]]!</p>
    
    <!-- JS内联 -->
    <script th:inline="javascript">
        var userName = /*[[${user.name}]]*/ '默认值';
        var userAge = /*[[${user.age}]]*/ 0;
        console.log(userName, userAge);
    </script>
四、常用工具类

Thymeleaf 提供内置工具类,可通过 #工具类名 调用方法,常用如下:

工具类 作用 示例
#strings 字符串操作 ${#strings.isEmpty(msg)}${#strings.toUpperCase(name)}
#numbers 数字格式化 ${#numbers.formatDecimal(price, 0, 2)}(保留 2 位小数)
#dates 日期格式化 ${#dates.format(createTime, 'yyyy-MM-dd HH:mm:ss')}
#lists 集合操作 ${#lists.isEmpty(userList)}${#lists.size(userList)}
#objects 对象判断 ${#objects.nullSafe(user.age, 0)}(null 时返回默认值 0)

示例:

复制代码
<!-- 字符串非空判断 -->
<div th:if="${#strings.isNotEmpty(msg)}">
    消息:<span th:text="${msg}"></span>
</div>

<!-- 日期格式化 -->
<div th:text="${#dates.format(user.createTime, 'yyyy-MM-dd')}"></div>

<!-- 数字保留2位小数 -->
<div th:text="${#numbers.formatDecimal(user.balance, 0, 2)}"></div>

总结

  1. 核心表达式${}(变量)、*{}(选择变量)、#{}(国际化)@{}(链接)、~{}(片段)是 Thymeleaf 最基础也是最核心的语法,需熟练掌握。
  2. 常用功能 :条件判断(th:if/th:switch)、循环遍历(th:each)、动态属性(th:class/th:value)是页面开发中高频使用的功能,结合工具类可提升开发效率。
  3. 代码复用 :通过 th:fragment + th:insert/replace 实现页面片段复用,是减少冗余代码的关键技巧。
相关推荐
彭于晏Yan40 分钟前
Spring AI(二):入门使用
java·spring boot·spring·ai
谁在黄金彼岸4 小时前
Spring Boot + WebFlux 全面使用指南
spring boot
希望永不加班4 小时前
SpringBoot 主启动类解释:@SpringBootApplication 到底做了什么
java·spring boot·后端·spring
智能工业品检测-奇妙智能4 小时前
国产化系统的性价比对比
人工智能·spring boot·后端·openclaw·奇妙智能
SmartBrain6 小时前
Spring Boot的高性能技术栈的工程实践
spring boot·后端·架构
dreamxian6 小时前
苍穹外卖day09
java·spring boot·tomcat·log4j·maven
q5431470877 小时前
VScode 开发 Springboot 程序
java·spring boot·后端
学习要积极7 小时前
Springboot图片验证码-EasyCaptcha
java·spring boot·后端
yuyu_03047 小时前
畜牧(牛)数字化管理系统系统概要
spring boot
波波七7 小时前
SSM与Springboot是什么关系? -----区别与联系
java·spring boot·后端