简介
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。主要用于编写动态页面。
从ThymeleafProperties可以看出Thymeleaf是一个视图解析器,将需要的界面放在calsspath:/templates/下。
作用
所有JSP可以使用的地方,Thymeleaf都可以使用,并根据Thymeleaf的优势,可以得出结论:Thymeleaf的作用就是取代JSP。
引入
我们可以创建SpringBoot项目的时候添加Thymeleaf模块
也可以在pom.xml文件中添加依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
使用
我们在Html界面引入Thymeleaf命名空间 xmlns:th="http://www.thymeleaf.org" ,这样才可以在标签中使用 th:这样的语法,所有的html元素都可以被Thymeleaf替换接管(th:元素名)
语法
${}:变量表达式
*{}:选择变量表达式
#{}:消息表达式
@{}:url
~{}:片段表达式
[[...]]:内联表达式,可以编写java代码
[(...)]:内联表达式,原文直接输出
简单使用
th:text 没转义
th:utext 转义
th:each 遍历
提取公共页面
1、th:fragment="变量名"
2、th:replace="~{页面名::变量名}"
3、如果要传递参数,可以直接使用()传参,接受判断即可。
th:replace="~{页面名::变量名(active="****")}"