SpringBoot集成Thymeleaf:模板引擎的详细使用教程

需积分: 0 0 下载量 10 浏览量 更新于2024-08-04 收藏 40KB DOCX 举报
"thymeleaf是spring推荐的模板引擎,用于在Spring应用程序中处理视图。本文档将详细介绍如何在SpringBoot项目中集成Thymeleaf以及其基本语法使用方法。" 在SpringBoot中集成Thymeleaf非常简单,可以通过Spring Initializr快速创建项目时选择Thymeleaf依赖,或者手动在`pom.xml`或`build.gradle`文件中添加Thymeleaf的依赖。对于Maven项目,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` Thymeleaf模板引擎以HTML作为基础,所以创建的视图文件通常以`.html`为扩展名。SpringBoot默认已经配置好Thymeleaf,包括默认的模板路径前缀`classpath:/resources/templates/`和后缀`.html`。 在开发阶段,为了便于调试,可以关闭Thymeleaf的页面缓存,通过在`application.properties`或`application.yml`文件中设置: ```properties # 默认为true,启用页面缓存 spring.thymeleaf.cache=false ``` 当项目上线后,可以根据需求重新开启缓存或保留此设置,以提高性能。 Thymeleaf的语法非常丰富,以下是一些基本示例: 1. `th:text` 属性用于显示文本内容。它可以覆盖原有内容或在无内容时自动生成标签: ```html <!-- 显示常量 --> <p th:text="hello"></p> <!-- 覆盖原有内容 --> <p th:text="hello">你好</p> <!-- 单标签形式 --> <p th:text="hello"/> ``` 2. 支持简单的数学运算: ```html <!-- 显示结果3 --> <p th:text="1+2"></p> <!-- 显示1+2=3 --> <p th:text="'1+2='+(1+2)"></p> ``` 3. 可以进行条件判断(三元运算): ```html <!-- 根据${user.age}判断是否已成年 --> <p th:text="${user.age} >= 18 ? '已成年' : '未成年'"></p> ``` 4. OGNL表达式 `${}` 用于获取Controller传递的数据,可以访问对象的属性和方法: ```html <!-- 显示用户名 --> <p th:text="'用户名:' + ${user.username}"></p> <!-- 调用getter方法 --> <p th:text="'用户名:' + ${user.getUsername()}"></p> <!-- 转换为全大写 --> <p th:text="'转换为全大写:' + ${user.username.toUpperCase()}"></p> ``` Thymeleaf还支持条件语句(如`th:if`和`th:unless`)、迭代(如`th:each`)、表单处理、国际化等更复杂的特性。通过这些特性,开发者可以轻松地构建动态和交互式的Web界面。在实际开发中,结合SpringBoot的RESTful API,Thymeleaf可以提供强大的视图渲染能力,为用户提供友好的用户体验。