ThymeLeaf
时间: 2025-04-10 13:27:53 浏览: 16
<think>嗯,用户想了解Thymeleaf模板引擎的使用教程和示例,我需要根据提供的引用内容来组织回答。首先,引用[1]提到Thymeleaf是最全的教程,应该先介绍基本概念和特点。然后引用[2]和[3]提到了SpringBoot集成和使用步骤,应该分步骤讲解如何配置和创建模板。
接下来,用户可能需要具体的示例,比如如何在HTML中使用Thymeleaf的表达式,所以需要举一个简单的例子,比如显示服务器时间的例子。然后,根据引用中的内容,Thymeleaf支持多种模板类型,这点也很重要,需要列出来。
此外,语法部分引用[2]提到标准表达式和th属性,应该详细说明常用语法,比如变量表达式、选择表达式、链接表达式等,并给出对应的示例代码。最后,应用场景部分可以结合引用中的信息,说明Thymeleaf在Web开发中的常见用途。
还要注意用户可能关心的问题,比如如何集成到SpringBoot,如何处理表单数据,以及Thymeleaf的优势,比如自然模板和与Spring的兼容性。确保回答结构清晰,分步骤讲解,并包含代码示例,这样用户能更好地理解和应用。</think>### Thymeleaf 模板引擎使用教程与示例
#### 1. **Thymeleaf 简介**
Thymeleaf 是一款用于 Web 和独立环境的现代服务器端 Java 模板引擎,支持 HTML、XML、JavaScript 等格式[^1]。其核心特点包括:
- **自然模板**:可直接在浏览器中打开预览,无需后端服务。
- **与 Spring 生态无缝集成**:尤其适合 Spring Boot 项目[^3]。
- **丰富的表达式语法**:支持变量、条件、循环等操作[^2]。
---
#### 2. **基础使用步骤**
##### (1) 添加依赖(Spring Boot 项目)
在 `pom.xml` 中引入 Thymeleaf 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
引用[3]指出,这是集成 Thymeleaf 的关键步骤。
##### (2) 创建模板文件
在 `resources/templates` 目录下新建 HTML 文件(如 `hello.html`),并添加命名空间:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf 示例</title>
</head>
<body>
<h1 th:text="${message}">默认文本</h1>
</body>
</html>
```
`th:text` 属性会替换默认文本为后端传递的值。
##### (3) 编写 Controller
通过 Spring MVC 控制器传递数据到模板:
```java
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "欢迎使用 Thymeleaf!");
return "hello";
}
}
```
##### (4) 访问结果
启动应用后访问 `http://localhost:8080/hello`,页面会显示动态渲染的文本。
---
#### 3. **常用语法示例**
##### (1) 变量表达式
```html
<p>用户名:<span th:text="${user.name}">未知</span></p>
```
`${}` 用于访问模型中的变量。
##### (2) 条件判断
```html
<div th:if="${user.isAdmin}">管理员权限</div>
<div th:unless="${user.isAdmin}">普通用户</div>
```
##### (3) 循环遍历
```html
<ul>
<li th:each="item : ${items}" th:text="${item}"></li>
</ul>
```
##### (4) 链接表达式
生成动态 URL:
```html
<a th:href="@{/user/{id}(id=${userId})}">用户详情</a>
```
##### (5) 表单绑定
处理表单提交:
```html
<form th:action="@{/submit}" th:object="${formData}" method="post">
<input type="text" th:field="*{username}">
<button type="submit">提交</button>
</form>
```
---
#### 4. **Thymeleaf 支持的模板类型**
- HTML(最常用)
- XML
- JavaScript
- CSS
- 纯文本[^1]
---
#### 5. **应用场景**
- **动态页面渲染**:结合后端数据生成 HTML。
- **邮件模板**:通过 Thymeleaf 生成格式化的邮件内容。
- **静态资源处理**:动态加载 CSS/JS 文件路径。
---
阅读全文
相关推荐

















