开发者社区 问答 正文

使用thymeleaf的教程是什么呢?

使用thymeleaf的教程是什么呢?

展开
收起
游客imunz7cl3kyog 2022-08-17 09:20:03 233 分享 版权
阿里云 AI 助理回答

Thymeleaf 是一个现代的服务器端 Java 模板引擎,它特别适合用于 Web 和独立环境中的 HTML、XML、文本模板的处理。Thymeleaf 的设计目标是提供一种优雅且高度可维护的方式来创建模板。它支持自然的模板技术,可以很好地与 HTML5 一起工作,并且能够很好地集成到基于 Spring 的项目中。

以下是一个简单的使用 Thymeleaf 的教程概览:

1. 添加依赖

在 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'

2. 配置 Spring Boot

application.propertiesapplication.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

3. 创建模板文件

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>

4. 控制器设置

在你的 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";
    }
}

5. 使用 Thymeleaf 表达式

Thymeleaf 提供了强大的表达式语言(EL)来处理数据绑定,如 ${...} 用于变量替换,*{...} 用于迭代,#{...} 用于国际化消息等。

6. 运行和测试

启动你的 Spring Boot 应用,然后访问 http://localhost:8080/(假设你的应用运行在本地的 8080 端口),你应该能看到 Thymeleaf 渲染后的页面内容。

以上就是使用 Thymeleaf 的基本步骤。更深入的学习,建议查阅 Thymeleaf 官方文档和实践更多的模板编写,以掌握其高级特性和最佳实践。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
收录在圈子:
+ 订阅
技术图谱:由专家组参与技术图谱的绘制与编写,知识与实践的结合让开发者们掌握学习路线与逻辑,快速提升技能 电子书:电子书由阿里内外专家打造,供开发者们下载学习,更与课程相结合,使用户更易理解掌握课程内容 训练营:学习训练营 深入浅出,专家授课,带领开发者们快速上云 精品课程:汇集知识碎片,解决技术难题,体系化学习场景,深入浅出,易于理解 技能自测:提供免费测试,摸底自查 体验实验室:学完即练,云资源免费使用
还有其他疑问?
咨询AI助理