使用thymeleaf的教程是什么呢?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
Thymeleaf 是一个现代的服务器端 Java 模板引擎,它特别适合用于 Web 和独立环境中的 HTML、XML、文本模板的处理。Thymeleaf 的设计目标是提供一种优雅且高度可维护的方式来创建模板。它支持自然的模板技术,可以很好地与 HTML5 一起工作,并且能够很好地集成到基于 Spring 的项目中。
以下是一个简单的使用 Thymeleaf 的教程概览:
在 Maven 项目中,你需要在 pom.xml
文件中添加 Thymeleaf 的依赖:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<!-- 版本号请根据实际情况填写 -->
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<!-- 版本号请根据实际情况填写 -->
<version>3.0.4.RELEASE</version>
</dependency>
如果是 Gradle 项目,则在 build.gradle
文件中添加:
implementation 'org.thymeleaf:thymeleaf-spring5:3.0.12.RELEASE'
implementation 'org.thymeleaf.extras:thymeleaf-extras-java8time:3.0.4.RELEASE'
在 application.properties
或 application.yml
中配置 Thymeleaf:
# application.properties 示例
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
或者在 application.yml
:
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
content-type: text/html
cache: false
在 src/main/resources/templates/
目录下创建一个 HTML 文件,例如 index.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}">默认标题</title>
</head>
<body>
<h1 th:text="'欢迎, ' + ${user.name}">欢迎页面</h1>
<p th:if="${not empty user.email}">
您的邮箱是: <span th:text="${user.email}"></span>
</p>
</body>
</html>
在你的 Spring 控制器中返回视图名或模型和视图:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
User user = new User("张三", "zhangsan@example.com");
model.addAttribute("user", user);
model.addAttribute("title", "Thymeleaf 示例页面");
return "index";
}
}
Thymeleaf 提供了强大的表达式语言(EL)来处理数据绑定,如 ${...}
用于变量替换,*{...}
用于迭代,#{...}
用于国际化消息等。
启动你的 Spring Boot 应用,然后访问 http://localhost:8080/
(假设你的应用运行在本地的 8080 端口),你应该能看到 Thymeleaf 渲染后的页面内容。
以上就是使用 Thymeleaf 的基本步骤。更深入的学习,建议查阅 Thymeleaf 官方文档和实践更多的模板编写,以掌握其高级特性和最佳实践。