当前位置: 首页 > news >正文

Thymeleaf 基础语法与标准表达式详解

关键词:Thymeleaf、Spring Boot、HTML 模板引擎、标准表达式、文本替换、条件判断、循环遍历


✅ 引言

在 Spring Boot 项目中,Thymeleaf 是一个非常流行且功能强大的服务器端 HTML 模板引擎。它支持自然模板(Natural Templates),即即使不运行后端也能直接在浏览器中查看页面效果。

本文将围绕 Thymeleaf 的基础语法与标准表达式 进行系统讲解,涵盖变量替换、条件判断、循环遍历、URL 处理、属性操作等核心知识点,并为每个小节提供完整的 HTML + Java 后端示例代码,帮助你快速上手 Thymeleaf 开发。


📌 一、Thymeleaf 简介与基本使用

1.1 引入依赖(Spring Boot 项目)

<!-- pom.xml -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

1.2 控制器返回视图名称

// HelloController.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class HelloController {@GetMapping("/hello")public String sayHello(Model model) {model.addAttribute("message", "Hello, Thymeleaf!");return "hello"; // 对应 templates/hello.html}
}

1.3 Thymeleaf 页面结构(hello.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Hello Thymeleaf</title>
</head>
<body><h1 th:text="${message}">默认标题</h1>
</body>
</html>

📌 访问 /hello 输出结果:

Hello, Thymeleaf!

📌 二、标准表达式类型详解

Thymeleaf 支持多种表达式,常见的有:

表达式描述
${...}变量表达式(用于获取模型数据)
*{...}选择变量表达式(适用于对象内部字段访问)
#{...}消息表达式(国际化支持)
@{...}链接 URL 表达式
~{...}片段表达式(用于引入其他模板片段)

📌 三、变量表达式 ${...}

示例代码

<p th:text="${'当前时间是:' + #dates.format(now, 'yyyy-MM-dd HH:mm:ss')}">时间</p>

后端传参:

model.addAttribute("now", new java.util.Date());

📌 输出效果:

当前时间是:2025-07-16 17:34:00

📌 四、选择变量表达式 *{...}

当对象上下文已知时使用,例如:

User user = new User("张三", 25);
model.addAttribute("user", user);
<div th:object="${user}"><p>姓名:<span th:text="*{name}"></span></p><p>年龄:<span th:text="*{age}"></span></p>
</div>

📌 输出结果:

姓名:张三
年龄:25

📌 五、消息表达式 #{...}(国际化支持)

5.1 定义消息文件(src/main/resources/messages.properties)

welcome.message=欢迎访问我们的网站!

5.2 使用消息表达式

<h2 th:text="#{welcome.message}">Welcome Message</h2>

📌 输出结果:

欢迎访问我们的网站!

📌 六、链接表达式 @{...}(生成 URL)

示例代码

<a th:href="@{/user/{id}(id=${user.id})}">查看详情</a>

user.id = 1001,则输出:

<a href="/user/1001">查看详情</a>

📌 七、片段表达式 ~{...}(模块化复用)

7.1 定义公共片段(fragments.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header"><meta charset="UTF-8"><title>公共头部</title>
</head>
</html>

7.2 引用片段

<div th:insert="~{fragments :: common_header}"></div>

📌 八、条件判断 th:if / th:unless

示例代码

<p th:if="${user.age >= 18}">您已成年。</p>
<p th:unless="${user.age >= 18}">您未成年。</p>

根据 user.age = 25 输出:

您已成年。

📌 九、循环遍历 th:each

示例代码(后端传 List)

List<String> fruits = Arrays.asList("苹果", "香蕉", "橙子");
model.addAttribute("fruits", fruits);
<ul><li th:each="fruit : ${fruits}" th:text="${fruit}"></li>
</ul>

📌 输出 HTML:

<ul><li>苹果</li><li>香蕉</li><li>橙子</li>
</ul>

📌 十、属性设置 th:attr 与快捷方式

10.1 设置任意属性

<input type="text" th:attr="placeholder=#{form.name}" />

10.2 快捷写法(推荐)

<input type="text" th:placeholder="#{form.name}" />

✅ 总结

表达式用途示例
${...}获取变量值th:text="${message}"
*{...}从对象中取值th:text="*{name}"
#{...}国际化消息th:text="#{welcome.message}"
@{...}构建 URLth:href="@{/user/{id}(id=1)}"
~{...}引入模板片段th:insert="~{fragments :: header}"
th:if条件渲染th:if="${user.isAdmin}"
th:each循环处理th:each="item : ${items}"
th:attr动态设置属性th:attr="data-id=${id}"

📚 推荐阅读

  • Thymeleaf 官方文档
  • Spring Boot 中 Thymeleaf 的最佳实践
  • Thymeleaf + Bootstrap 实现动态表格
http://www.dtcms.com/a/282558.html

相关文章:

  • 如何区分Bug是前端问题还是后端问题?
  • LeetCode经典题解:141、判断链表是否有环
  • 【LeetCode】链表相关算法题
  • Node.js Process Events 深入全面讲解
  • 1.3 vue响应式对象
  • FATFS文件系统原理及其移植详解
  • PyTorch 损失函数详解:从理论到实践
  • 嵌入式学习-PyTorch(5)-day22
  • 【深度学习基础】PyTorch中model.eval()与with torch.no_grad()以及detach的区别与联系?
  • Vue 结合 Zabbix API 获取服务器 CPU、内存、GPU 等数据
  • 数据结构自学Day8: 堆的排序以及TopK问题
  • 前端Vue中,如何实现父组件打开子组件窗口等待子组件窗口关闭后继续执行父组件逻辑
  • DeepSeek(18):SpringAI+DeepSeek大模型应用开发之会话日志
  • 单片机(STM32-中断)
  • JS逆向 - YandexSmartCaptcha (worker线程)
  • 基于WebRTC构建应用的可复用模块
  • 下载webrtc M114版本源码只能使用外网googlesource源-命令版
  • i.mx8 RTC问题
  • TEngine学习
  • 【Noah-MP模型】陆面生态水文模拟与多源遥感数据同化的实践技术应用
  • JavaScript进阶篇——第六章 内置构造函数与内置方法
  • alpineLinux修改包管理为国内源
  • 越野小车结构设计\越野小车设计cad【6张】三维图+设计说明书
  • 【Java】【力扣】101.对称二叉树
  • 数据结构与算法——Leetcode215. 数组中的第K个最大元素
  • 中国1km分辨率逐月平均气温数据集 - matlab按shp批量裁剪
  • Git远程仓库与协作技巧详解
  • 【add vs commit】Git 中的 add 和 commit 之间的区别
  • 秘塔AI搜索的深度研究推出:它的“免费午餐”还能走多远?
  • NULL值处理:索引优化与业务设计实践指南