springthymeleaf
导入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application中配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
引入命名空间
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello</h1>
<p th:text="${hello}"></p>
</body>
</html>
使用在属性前加th:
<h1 th:inline="text">Hello</h1>
<p th:text="${hello}"></p>
属性
1. th:if
<p th:if="${hello}"></p>
<p th:if="${hello} == null"></p>
<p th:if="${hello} == ''"></p>
<p th:if="${not hello}"></p>
2. th:each
<tr th:each="user : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>
<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>
- index,从0开始的角标
- count,元素的个数,从1开始
- size,总元素个数
- current,当前遍历到的元素
- even/odd,返回是否为奇偶,boolean值
- first/last,返回是否为第一或最后,boolean值
3. th:switch
<div th:switch="${user.role}">
<p th:case="'admin'">用户是管理员</p>
<p th:case="'manager'">用户是经理</p>
<p th:case="*">用户是别的玩意</p>
</div>
4. js模板
<script th:inline="javascript">
const user = {};
const age = 20;
console.log(user);
console.log(age)
</script>
5. ${} *{} ~{} @{}的区别
- ${} 获取域属性内容,session,request,applicationContext
- *{} 在th:object的标签内使用 *{}来获取th:object中对象的属性
- ~{}
- @{} 用于链接获取项目名称