Springboot中Thymeleaf基本使用
1.springboot整合 thymeleaf
1.1导入依赖
<!-- spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.0</version>
</dependency>
1.2 页面引入命名空间
在html中引入thymeleaf命名空间,即可用thymeleaf表达式
<html xmlns:th="http://www.thymeleaf.org" lang="en">
2. thymeleaf
基本语法
页面引入命名空间后针对后端存储在session中的数据可通过以下方式来get
2.1 取值
把数据存入session
后,通过两种方式取值
[[${对象.属性的get方法}]] ex:user.getId()
<div th:text="${对象.属性的get方法}"></div>
2.2 条件选择和循环控制
-
<!-- 简单if --> <div th:if="${变量值 == null}" th:text="xxxx or ${变量值}"></div> <!-- 通过三目运算符 实现if-else --> <td th:text="${user.getGender()==0?'男':'女'}"></td>
-
<tbody> <tr th:each="user:${allUsers}"> <!-- 从session 中取值 然后迭代该数据 --> <!-- 两种取值的方式 --> <td th:text="${user.getId()}"></td> <td>[[${user.getName()}]]</td> <!-- 通过三目运算符实现if-else 一般在前端 都是通过这个实现if-else 划重点!! --> <td th:text="${user.getGender()==0?'男':'女'}"></td> </tr> </tbody>
2.3 表达式
所有的表达式都必须嵌入在一个完整的html标签中,如完整的、
中,使用前需要引入thymeleaf的命名空间
- @{} 超链接url表达式 导入外部资源 ex:
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
- ${} 变量表达式 一般用作取值
- *{} 模板页面访问
- #{} 消息表达式 国际化
3.常用的 工具类
# 格式化日期
#dates
# 使用标准区域设置格式格式化日历
#calendars
#格式化整数
#numbers
# 对字符串操作
#strings
# 当obj不为空时,返回obj,否则返回default默认值
#objects
# 评估条件, 类似于 th:if 标签
#bools
# 数组工具类
#arrays
# list 集合工具类
#lists
# set 集合工具类
#sets