1、简介
Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎 (之前用的jsp也是模版引擎但是比较弱),是springboot官方推荐使用的模板引擎。
2、配置
(1)Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)yaml关闭缓存
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。
# 关闭Thymeleaf的缓存
spring:
thymeleaf:
cache:
false
3、基本用法
在html标签内的属性前加th:,大部分属性都支持的。
(1)基本表达式
这里着重介绍变量表达式 和URL表达式
变量表达式${name}:如果session或model中有名为name的key,就可以取出name的value。
<span th:text="${name}">
URL表达式@{/…/…},在/templates目录下会把静态资源(css,js,img)过滤,但是如果url由Thymeleaf管理就可以成功访问资源。'/'指的是resources/static目录
<link th:href="@{/css/bootstrap.min.css}"/>
(2)常用标签
-
文本替换
<p th:text="${user.name}">name</p>
-
属性赋值
<input th:value="${user.name}" >
-
替换资源/超链接
<script type="text/javascript" th:src="@{/index.js}"></script>
-
点击事件
<p th:onclick="'getCollect()'"></p>
-
for-each
<tbody th:each="it:${list}"> <tr> <th th:text="${it.getId()}" ></th> <td th:text="${it.getUsername()}"></td> </tr> </tbody>
-
if
<a th:if="${userId == collect.userId}" >
-
switch-case
<!-- th:switch / th:case --> <div th:switch="${user.name}"> <p th:case="'admin'">User is an administrator</p> <!-- *: case的默认的选项 --> <p th:case="*">User is some other thing</p> </div>
-
公共页面
前端其实许多页面组成是重复的,比如侧边栏、头部导航栏、底部导航栏等,为了提高代码复用性可以使用公共页面。th:fragment标记此标签为模板,根据名字可以引用模板
<div class="navMenu" th:fragment="header"> <div class="navMenuContain"> 导航菜单 </div> </div>
th:replace引用
表示引用cmment目录下的comment.html的header模板<div th:replace="~{comment/comment::headbar}"></div>
th:include引用
<div th:insert="~{comment/comment::headbar}"></div>
include和replace区别
th:include:引入子模块的children,依然保留父模块的tag。
th:replace:引入子模块的所有,不保留父模块的tag。
(3)传参
在连接地址的后面加上(key=‘value’),下面表示点击这个超链接会向/index.html传入名为l的参数,参数值是’参数’。
<a class="btn btn-sm" th:href="@{/index.html(l='参数')}">11111</a>
4、常用函数
这篇博客大佬列举的很全Thymeleaf 常用函数_thymeleaf 函数-CSDN博客