Thymeleaf是SpringBoot官方所推荐使用的,Thymeleaf是动静分离的,页面中的动态标签是需要传递有数据的时候才会渲染,不然就是原本默认的静态的样子
添加Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
无需指定版本号,spring-boot-dependencies.pom中已指定
Thymeleaf常用语法
<p>[[${abc+'123'}]]</p> 将控制器传入的数据显示在<p></p>中
<title th:text="${title}">默认的标题</title>//若title为空就显示默认的标题,若不为空则显示title的值,title的值是控制器传入的
渲染User这个对象的信息我们可以这样## 标题
<div>
<h2 th:text="${user.getUsername()}"></h2>
<p th:text="${user.getAge()}"></p>
</div>
还可以不使用get的方式,直接使用属性名
<h2 th:text="${user.username}" ></h2>
th:if
th:if 通过布尔值决定这个元素是否渲
<p th:if="${user.isVip}">会员</p>
th:each
th:each 可以迭代循环出数据,前面我们User对象里面的tags是一个数组,我们来渲染一下
<tr th:each="cs,rowInfo : ${visitor_list}">
<th>[[${rowInfo.count}]]</th>
<td>[[${cs.ip}]]</td>
<td>[[${cs.visitorname}]]</td>
<td>[[${cs.state}]]</td>
<td>[[${cs.visittime}]]</td>
<td>[[${cs.customerserviceid}]]</td>
</tr>
th:switch
<div th:switch="${user.getSex()}">
<p th:case="'1'">男</p>
<p th:case="'2'">女</p>
<p th:case="*">默认</p>
</div>
碎片(组件)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="com1">
this is com1
</footer>
<footer th:fragment="com2">
this is com2
</footer>
在其它页面中引用
<!--replace fragment表示fragment.html文件-->
<div th:replace="~{fragment::com1}"></div>
<!--insert fragment表示fragment.html文件->
<div th:insert="~{fragment::com2}"></div>