Thymeleaf学习教程
一、Thymeleaf简介
Thymeleaf是一个Java模板引擎,它能够处理HTML、XML、JavaScript、CSS甚至纯文本。Thymeleaf的主要特点是它能够在浏览器中直接显示模板(具有自然模板模式),并且可以在服务器端和客户端进行渲染,这使得它在Web开发中非常流行,特别是在基于Java的Web框架(如Spring Boot)中。
二、环境搭建
1. 创建Maven项目(以Maven为例)
- 使用你喜欢的IDE(如IntelliJ IDEA或Eclipse)创建一个新的Maven项目。
- 在
pom.xml
文件中添加以下依赖:
<project>
<!-- 其他项目配置 -->
<dependencies>
<!-- Thymeleaf核心依赖 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.14.RELEASE</version>
</dependency>
<!-- 与Spring集成的依赖(如果用于Spring项目) -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.14.RELEASE</version>
</dependency>
</dependencies>
</project>
2. 创建基本项目结构
- 在
src/main/resources
目录下创建templates
文件夹,这是Thymeleaf默认的模板存放位置。
三、基础语法
1. 命名空间声明
- 在HTML文件的
<html>
标签中添加Thymeleaf的命名空间声明:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2. 文本替换(th:text
)
- 这是最基本的Thymeleaf属性,用于替换HTML标签中的文本内容。
- 示例:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>
<p th:text="'Hello, Thymeleaf!'">This is a default text</p>
</body>
</html>
- 在这个例子中,
<p>
标签中的默认文本This is a default text
将会被Hello, Thymeleaf!
替换。
3. 表达式求值
- 变量表达式(
${...}
)- 用于获取服务器端传递过来的变量值。
- 首先,在Java代码(如Spring控制器)中设置一个变量并将其添加到模型中:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@RequestMapping("/")
public String index(Model model)