Thymeleaf模板引擎 常用的用法整理总结

文章目录

一、前言

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的html文档。从字面上理解模板引擎,最重要的就是模板二字,这个意思就是做好一个模板后套入对应位置的数据,最终以html的格式展示出来,这就是模板引擎的作用。

  • 动静分离: Thymeleaf选用html作为模板页,这是任何一款其他模板引擎做不到的!Thymeleaf使用html通过一些特定标签语法代表其含义,但并未破坏html结构,即使无网络、不通过后端渲染也能在浏览器成功打开,大大方便界面的测试和修改。
  • 开箱即用: Springboot官方大力推荐和支持,Springboot官方做了很多默认配置,开发者只需编写对应html即可,大大减轻了上手难度和配置复杂度。

二、配置

1.先在SpringBoot项目中引入Thymeleaf依赖

xml 复制代码
<!-- 整合thymeleaf模板引擎 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.在SpringBoot配置文件application.properties中添加以下配置:

java 复制代码
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html

3.每个html页面都要加上th名称空间:xmlns:th="http://www.thymeleaf.org"

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<style>
</style>
<body>
	<div></div>
</body>
<script type="text/javascript">
</script>
</html>

三、基本语法

1.变量表达式

在Thymeleaf中可以通过${...}进行取值

①文本替换和html的文本替换

文本替换

html 复制代码
<div th:text="${username}"></div>

html的文本替换

html 复制代码
<div th:utext="${username}"></div>

补充:
[[${}]]相当于th:text,会解析为普通文本。
[(${})]相当于th:utext,会解析为html。

例子:

html 复制代码
<div>[[${str}]]</div>
html 复制代码
<div>[(${str)]]</div>
html 复制代码
th:οnclick="removeOrder([[${order.id}]])"

②属性值替换

凡是标签具有的属性,都可以用th:进行绑定然后替换成我们自己的值,以下我们列举两个例子:

html 复制代码
<input th:value="${username}"></input>
html 复制代码
<input th:id="${username}"></input>

③对象中字段取值

以下三种写法都能实现获取对象中某个字段的值

html 复制代码
<div th:text="${user.username}"></div>
html 复制代码
<div th:text="${user['username']}"></div>
html 复制代码
<div th:text="${user.getUsername()}"></div>

④字符串拼接

html 复制代码
<div th:text="'大家好,我是' + ${user.username}"></div>

⑤逻辑判断

th:if里面判断结果如果为true,这个div标签才会在页面上显示,如果为false,这个div标签则不会在页面上显示。

html 复制代码
<div th:if="${number} == 100">哈哈</div>

unless实际上是对th:if用法取反。

html 复制代码
<div th:unless="${number} == 100">哈哈</div>

⑥迭代遍历

html 复制代码
<!--
user :	第1个值,代表每次迭代出对象,名字任意取
iterStat : 第2个值,代表每次迭代器内置对象, 名字任意取, 并有如下属性:
   index : 当前迭代下标 0 开始
   count : 当前迭代下标 1 开始
   size : 获取总记录数
   current : 当前迭代出的对象
   even/odd : 当前迭代是偶数还是奇数 (1开始算,返回布尔值)
   first : 当前是否为第一个元素
   last : 当前是否为最后一个元素
-->
<table border="1">
    <tr border th:each="user,iterStat: ${userList}">
        <td th:text="${iterStat.count}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${iterStat.size}"></td>
        <td th:text="${iterStat.even? '偶数':'奇数'}"></td>
        <td th:text="${iterStat.first}"></td>
        <td th:text="${iterStat.last}"></td>
    </tr>
</table>

⑦运算

算术运算:支持的算术运算符(+ - * / %

html 复制代码
<div th:text="${number * 2}">哈哈</div>
html 复制代码
<div th:text="${number} - 100">哈哈</div>

三元运算符

html 复制代码
<div th:text="${number == 10 ? '是' : '不是'}"></div>

⑧ Switch

html 复制代码
<div th:switch="${user.role}">
    <p th:case="'teacher'">教师</p>
    <p th:case="'student'">学生</p>
    <p th:case="*">其它</p>
</div>
  • 需要注意的是,一旦有一个th:case成立,其它的则不再判断。与Java中的Switch是一样的。
  • th:case="*" 表示默认,放最后。

⑨ 内置对象

Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用#对象名来引用。

对象 作用
#dates 处理java.util.date的工具对象
#calendars 处理java.util.calendar的工具对象
#numbers 用来对数字格式化的方法
#bools 用来判断布尔值的方法
#arrays 用来护理数组的方法
#strings 用来处理字符串的方法
#lists 用来处理List集合的方法
#sets 用来处理set集合的方法
#maps 用来处理map集合的方法

我们来看几个例子:

1.获取今天日期, today是获取后端传过来的Date对象

html 复制代码
<span th:text="${#dates.format(today,'yyyy-MM-dd')}"></span>
html 复制代码
<span th:text="${#calendars.format(today,'yyyy-MM-dd')}"></span>

2.设置千位分隔符, COMMA表示千位分隔符逗号 2表示对不够位数的数字进行补0

html 复制代码
<p th:text="${#numbers.formatInteger('1000000000', 2, 'COMMA')}"></p> //1,000,000,000
html 复制代码
<p th:text="${#numbers.formatInteger('1000', 5, 'COMMA')}"></p> // 01,000

3.判断字符串是否为空(null空字符串

html 复制代码
<p th:text="${#strings.isEmpty(str)}"></p>

4.获取列表的长度

html 复制代码
<span th:text="${#lists.size(userList)}"></span>

2.链接表达式

在Thymeleaf 中,如果想引入链接比如href,src,需要使用@{资源地址}引入资源。其中资源地址可以是static目录下的静态资源,也可以是互联网中的绝对资源

html 复制代码
<link rel="stylesheet" type="text/css" th:href="@{css1.css}">
<script type="text/javascript" th:src="@{a.js}"></script>
html 复制代码
<a class="test" th:href="@{https://www.baidu.com/}">哈哈哈</a>

3.选择变量表达式

${}*{}差别不大,主要区别就是:只要没有选定的对象${}*{}的语法就完全一样。

而选定对象是指使用th:object属性的表达式的结果。

html 复制代码
<div th:object="${user}">
    <div th:text="*{username}"></div>
    <div th:text="*{role}"></div>
</div>

当然*{}也可和${}混用。上面的代码如果不使用选定对象,完全等价于:

html 复制代码
<div>
    <div th:text="*{user.username}"></div>
    <div th:text="${user.role}"></div>
</div>

4.消息表达式

文本外部化是从模板文件中提取模板代码的片段,以便可以将它们保存在单独的文件(通常是.properties文件)中,文本的外部化片段通常称为"消息"。通俗易懂的来说#{}语法就是用来读取配置文件中数据的。

使用之前要先在配置文件application.properties中加入这行配置,用于指定读取文件的路径。

java 复制代码
spring.messages.basename=templates/properties

然后创建个a.properties放到这个路径下面

a.properties文件中写入以下信息:

java 复制代码
aa.username=杨杨吖

页面中读取配置文件的信息:

html 复制代码
<div th:text="#{aa.username}"></div>

5.代码块表达式

代码块表达式支持两种语法结构:
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}

  • templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
  • fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"
  • id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。

  • th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中
  • th:replace:将代码块片段整个替换使用了th:replace的HTML标签中
  • th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中

index.html里面代码:

这里注意: ~{footer :: copy}footer :: copy 等价,可以简写。

html 复制代码
<div th:insert="~{footer :: copy}"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: #idCopy"></div>

footer.html里面代码:

html 复制代码
<footer th:fragment="copy">
    &copy; 2023 The Good Thymes Virtual Grocery
</footer>

<footer id="idCopy">
    &copy; 2024 The Good Thymes Virtual Grocery
</footer>

运行结果如下:

html 复制代码
<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
    <footer>
    &copy; 2023 The Good Thymes Virtual Grocery
    </footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
	&copy; 2023 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
	&copy; 2024 The Good Thymes Virtual Grocery
</div>
相关推荐
用户908324602732 天前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
用户8307196840823 天前
Spring Boot 集成 RabbitMQ :8 个最佳实践,杜绝消息丢失与队列阻塞
spring boot·后端·rabbitmq
Java水解3 天前
Spring Boot 视图层与模板引擎
spring boot·后端
Java水解3 天前
一文搞懂 Spring Boot 默认数据库连接池 HikariCP
spring boot·后端
洋洋技术笔记3 天前
Spring Boot Web MVC配置详解
spring boot·后端
初次攀爬者4 天前
Kafka 基础介绍
spring boot·kafka·消息队列
用户8307196840824 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Java水解4 天前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
初次攀爬者5 天前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺5 天前
搞懂@Autowired 与@Resuorce
java·spring boot·后端