Thymeleaf
一、概述
- 是一个现代的服务器端的Java模板引擎,适用于Web和独立环境
- SpringBoot官方推荐的模板引擎
二、工作原理
三、快速入门
1. 实现步骤
- 导入依赖
- 配置文件
- 写Controller
- 模板文件
2. 具体操作
2.1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2 配置文件
spring:
thymeleaf:
#关闭缓存
cache: false
#检查
check-template: true
2.3 写controller
@Controller
@RequestMapping("/thymeleaf")
@Slf4j
public class ThymeleafController {
@RequestMapping("/test01")
public String test1(Model model){
model.addAttribute("name", "张三");
return "success";
}
}
2.4 模板文件
resources下-templates下-html文件
<p th:text=“${name}”>小强</p>
th: 代表thymeleaf的指令,必须作为html的属性存在,不能单独使用
四、配置
五、常用指令
1. th:text
- 用来获取文本数据
controller文件
model.addAttribute("name", "张三");
模板文件
<p th:text="${name}">xxx</p>
- 三元运算符
controller文件
model.addAttribute("age", 18);
模板文件
<h2 th:text="${age >= 18 ? '成年人' : '未成年人'}"></h2>
- 字符串拼接
模板文件
<h3 th:text="|姓名:${name},性别:${age}|"></h3>
2. th:utext
获取解析HTML标签
controller文件
model.addAttribute("content", "<h1>这是一个h1标题</h1>");
模板文件
<span th:utext="${content}"></span>
3. th:if th:unless
条件判断,
th:if:条件返回ture:则解析
th:unless:条件返回false:则解析
<h4 th:if="${age >= 18}">年龄到达18岁,允许进入该网站</h4>
<h4 th:unless="${age >= 18}">年龄没有到达18岁,多吃点,快点长大</h4>
4. th:each
遍历
controller文件
List<Employee> emps = employeeMapper.findAllAndDept();
model.addAttribute("emps", emps);
模板文件
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>row</th>
<th>id</th>
<th>empName</th>
<th>birthday</th>
<th>salary</th>
<th>dept</th>
</tr>
<!--
th:each="迭代的元素,状态变量 : ${集合数据}"
-->
<tr th:each="emp,empStat : ${emps}">
<th th:text="${empStat.index + 1}">id</th>
<th th:text="${emp.id}">id</th>
<th th:text="${emp.empName}">empName</th>
<!--
#xxx : 代表thymeleaf的内置对象
dates : 用来操作时间
format : 格式化
参数1:要操作的时间
参数2:要显示的时间格式
-->
<th th:text="${#dates.format(emp.birthday, 'yyyy-MM-dd')}">birthday</th>
<!--
numbers : 用来操作数值
formatDecimal : 格式化
参数1:要操作的数值
参数2:要保留的整数位,如果0,代表不对整数操作
参数3:要保留的小数位
-->
<th th:text="${#numbers.formatDecimal(emp.salary/100.0, 0, 2)}">salary</th>
<th th:text="${emp.department.deptName}">dept</th>
</tr>
</table>
5. th:inline
js中获取模型数据
模板文件
<body>
<button onclick="getName()">获取模型数据的name</button>
</body>
<!-- 在js中使用thymeleaf -->
<script th:inline="javascript">
function getName() {
alert([[${name}]]);
}
</script>