1.Thymeleaf模板布局
Thymeleaf是一个跟Velocity、FreeMarker类似的模板引擎。它拥有如下特点:
(1)自然模板,原型及页面。开箱即用。
(2)语法易懂,支持OGNL、SpringEL。
(3)遵循web标准
2.springBoot集成Thymeleaf
build.gradle添加对Thymeleaf的依赖
添加thymeleaf指定版本:
// 自定义 Thymeleaf 和 Thymeleaf Layout Dialect 的版本
ext['thymeleaf.version'] = '3.0.3.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.2.0'
ok,配置文件搞定了,接下来我们开始写代码。
3.Thymeleaf实战-前后台编码
(1)代码结构
(2)application.properties配置
# THYMELEAF
spring.thymeleaf.encoding=UTF-8
# 热部署静态文件
spring.thymeleaf.cache=false
# 使用HTML5标准
spring.thymeleaf.mode=HTML5
(3)Thymeleaf前端页面
list.htm
区分:th:insert & th:replace & th:include
userModel是服务端返回前端的数据模型
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to waylau.com</h3>
<div>
<a href="/users/form.html">创建用户</a>
</div>
<table border="1">
<thead>
<tr>
<td>ID</td>
<td>Age</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">没有用户信息!!</td>
</tr>
<tr th:each="user : ${userModel.userList}">
<td th:text="${user.id}">1</td>
<td th:text="${user.age}">11</td>
<td><a href="view.html" th:href="@{'/users/' + ${user.id}}"
th:text="${user.name}">waylau</a></td>
</tr>
</tbody>
</table>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
(4)后台编码
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
/**
* 从 用户存储库 获取用户列表
* @return
*/
private List<User> getUserlist() {
return userRepository.listUser();
}
/**
* 查询所用用户
* @return
*/
@GetMapping
public ModelAndView list(Model model) {
model.addAttribute("userList", getUserlist());
model.addAttribute("title", "用户管理");
return new ModelAndView("users/list", "userModel", model);
}
}
在日常使用Thymeleaf的开发过程中,大家可参考基本语法进行编码。
https://blog.youkuaiyun.com/zrk1000/article/details/72667478
https://www.thymeleaf.org/apidocs/thymeleaf/3.0.9.RELEASE/