本文档介绍了如何在Spring Boot 2项目中集成Thymeleaf 3,并详细讲解了Thymeleaf 3的基本语法和高级特性,帮助开发者快速上手。
## Spring Boot与Thymeleaf整合
### 1. 导入起步依赖
```xml
org.springframework.boot
spring-boot-starter-thymeleaf
```
### 2. 更改引入版本
```xml
3.0.2.RELEASE
2.1.1
```
Spring Boot自带的Thymeleaf依赖版本为2.1.3,使用`thymeleaf-layout-dialect`时需注意:
- 使用3或以上版本的Thymeleaf需要配合至少2.x版的`thymeleaf-layout-dialect`。
- 锁定特定版本时,请不要用`thymeleaf.version`标签,以避免与Spring Boot内部依赖冲突。应使用`springboot-thymeleaf.version`来锁定版本。
### 3. 配置文件配置
```properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
```
`cache=false`用于热部署时关闭缓存。
## 语法
### 替换标签体内容
```html
显示欢迎
显示欢迎
```
### 替换属性
```html
显示欢迎
```
### 在表达式中访问属性域
```html
访问属性域
方式一
方式二
访问Session域和Application域
```
### 解析URL地址
```html
解析URL地址,获取ContextPath的值
@{}是把ContextPath附加到指定路径前。
示例文本
```
### 直接执行表达式
```html
直接执行表达式
[]
```
### 分支与迭代
#### if 判断字符串是否为空
```html
if判断字符串是否为空
不空时显示此行文本
非空时不显示,反之则显示。
```
#### 测试迭代
```html
```
### 引入代码片段
1. `insert`:将指定的fragment插入到当前标签的位置。
2. `replace`:使用被引入的代码替换原有的内容。
3. `include`:仅包含fragment中的子元素,不包括其自身的结构。
示例:
```html
内嵌文本
```
渲染后的HTML:
```html
被包含的内容2222,背景黄色。
```
确保 :: 左边的值拼前后缀后能找到文件,并且右边的是正确的片段名。