1. Thymeleaf
1.1 模板引擎
- Velocity
- FreeMarker
- Groovy
- Beetl
1.2 特点
- 支持 html 原型,可以在 html 标签里增加额外的属性来达到
模板 + 数据
的展示方式 - Thymeleaf 模板可以静态地运行,当有数据返回时,Thymeleaf 标签会动态地替换静态内容
- 开箱即用,支持 JSTL, OGNL 表达式
示例:<span th:text="${userName}">hello</span>
从服务器读取到数据时,用 userName 覆盖 hello;若未读取,直接使用 hello
2. Thymeleaf语法
-
th:
开头
3. 实战
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
spring:
thymeleaf:
cache: false # 开发时关闭缓存,可查看实时页面
mode: LEGACYHTML5 # 非严格的html 格式, nekohtml提供的
encoding: UTF-8
servlet:
content-type: text/html
index.html 文件
声明名称空间 xmlns:th="http://www.thymeleaf.org
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Demo</title>
</head>
<body>
<span th:text="${user.name}">other</span>
</body>
</html>
测试
@Controller // 返回 html页面
public class IndexController {
@GetMapping(value = {"", "index"})
public String index(Model model) {
User user = new User("Tinyspot", 20);
model.addAttribute("user", user);
// Thymeleaf 模板自动添加后缀 .html
return "index";
}
}
网友评论