1. 初识Thymeleaf
Thymeleaf是一个Java库,用于服务器端模板引擎,用于生成HTML5、XML和其他类型的文本。它广泛用于Web开发中,特别是在Spring框架中。Thymeleaf的主要特点是简洁、灵活且易于使用。
2. 环境搭建
要开始使用Thymeleaf,首先需要搭建一个Java开发环境,并添加Thymeleaf依赖到项目中。以下是一个基本的Maven项目结构:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
3. 页面构建
在Thymeleaf中,页面是由HTML模板和Thymeleaf模板片段组成的。以下是一个简单的Thymeleaf页面示例:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${title}">Hello, World!</h1>
<div th:each="item : ${items}">
<p th:text="${item}">Item details</p>
</div>
</body>
</html>
在这个例子中,th:text用于绑定数据到页面元素,th:each用于遍历列表。
4. 数据展示
Thymeleaf支持多种数据类型,包括字符串、数字、日期等。以下是一些常用的数据绑定示例:
<!-- 文本 -->
<p th:text="${user.name}">User's name</p>
<!-- 链接 -->
<a th:href="@{/users/{id}(id=${user.id})}">User details</a>
<!-- 图片 -->
<img th:src="@{/images/${user.image}}" alt="User image" />
<!-- 日期 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}">User's birthday</p>
5. 控制结构
Thymeleaf提供了多种控制结构,如条件判断、选择和迭代。
<!-- 条件判断 -->
<div th:if="${user.age > 18}">
<p>User is an adult</p>
</div>
<!-- 选择 -->
<div th:switch="${user.status}">
<p th:case="active">User is active</p>
<p th:case="inactive">User is inactive</p>
<p th:case="*">User has an unknown status</p>
</div>
<!-- 迭代 -->
<div th:each="item : ${items}">
<p th:text="${item}">Item details</p>
</div>
6. 表单处理
Thymeleaf支持表单处理,包括提交、验证和重定向。
<form th:action="@{/submit}" th:method="post">
<input type="text" name="username" th:value="${user.name}" />
<input type="submit" value="Submit" />
</form>
7. 集成Spring
在Spring框架中,可以使用@Controller和@RestController注解来处理Thymeleaf模板。以下是一个简单的示例:
@Controller
public class ExampleController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("user", new User("John Doe", 30));
return "index"; // Thymeleaf模板文件名
}
}
8. 总结
通过本文,您应该已经掌握了Thymeleaf模板渲染的基本流程,从页面构建到数据展示。在实际项目中,您可以根据需求不断学习和探索Thymeleaf的高级特性。
