avatar

Thymeleaf 模板引擎

Thymeleaf 简介

官网部分翻译:反正就是各种好

  • Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎
  • Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。

导入

创建SpringBoot项目,在选择模块 Template Engines 中勾选 Thymeleaf

或者在创好项目之后再pom.xml文件中导入依赖

1
2
3
4
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

在项目resource目录中的templates创建html页面

创建好html后需要在顶部的 html 标签中声明 thymeleaf 就可以使用它的语法了

1
<html lang="en" xmlns:th="http://www.thymeleaf.org">

使用前在application.properties中配置

1
spring.thymeleaf.cache=false

作用:关闭Thymeleaf的缓存,修改页面后立即生效

语法

一、标准表达式语法

它又分为:

  • 消息
  • 变量
  • 选择表达式
  • 链接URL
  • 片段
  • 文字
  • 附加文本
  • 字面替代
  • 算术运算
  • 比较与平等
  • 条件表达式
  • 默认表达式
  • 无操作令牌
  • 数据转换/格式化
  • 预处理

变量

1
<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

意味着 < span >标签中的内容会被表达式${today}的值所替代,无论模板中它的内容是什么,之所以在模板中“多此一举“地填充它的内容,完全是为了它能够作为原型在浏览器中直接显示出来。
假设today的值为2015年8月14日,那么渲染结果为:< p >Today is: 2015年8月14日.< /p >。可见Thymeleaf的基本变量和JSP一样,都使用${.}表示获取变量的值。

URL

URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{…}来处理的。Thymeleaf支持绝对路径URL:

1
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

同时也能够支持相对路径URL:

另外,如果需要Thymeleaf对URL进行渲染,那么务必使用th:hrefth:src等属性,下面是一个例子

1
2
3
4
5
6
7
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

几点说明:
上例中URL最后的(orderId=${o.id})表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性@{…}表达式中可以通过{orderId}访问Context中的orderId变量@{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order

字符串替换

1
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

一种更简洁的方式是:

1
<span th:text="|Welcome to our application, ${user.name}!|">

当然这种形式限制比较多,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等

运算符

1
<span th:with="isEven=(${prodStat.count} % 2 == 0)"></span>

逻辑运算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>时需要用它的HTML转义符:

二、常用的表达式

for循环

使用th:each标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<table border="1">
<tr>
<th>usrId</th>
<th>usrName</th>
<th>usrRoleId</th>
<th>index</th>
</tr>
<tr th:each="user,status : ${users}">
<td th:text="${user.usrId}">1</td>
<td th:text="${user.usrName}"></td>
<td th:text="${user.usrRoleId}">惑惑惑惑</td>
<td th:text="${status.index}">0</td>
</tr>
</table>

status 表示循环状态变量,属性有:

  • index:当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

if / unless条件求值

1
2
<a th:if="${flag == 'yes'}" th:href="@{http://www.baidu.com/}">百度</a><br>
<a th:unless="${flag == 'no'}" th:href="@{http://www.baidu.com/}">百度亿下</a>

Thymeleaf中使用th:if和th:unless属性进行条件判断,上面的例子中,div 标签只有在th:if中条件成立时才显示:

th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

switch

1
2
3
4
5
6
<div th:switch="${sex}">
<p th:case="'woman'">她是一个姑娘...</p>
<p th:case="'man'">这是一个爷们!</p>
<!-- *: case 的默认的选项 -->
<p th:case="*">未知性别的一个家伙。</p>
</div>

内嵌变量

为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:

  • dates : java.util.Date的功能方法类。
  • calendars : 类似#dates,面向java.util.Calendar
  • numbers : 格式化数字的功能方法类
  • strings : 字符串对象的功能类
  • objects: 对objects的功能类操作。
  • bools: 对布尔值求值的功能方法。
  • arrays:对数组的功能类方法。
  • lists: 对lists功能类方法
  • sets
  • maps

常用th标签

标签 说明 例子
th:id 替换id < input th:id=”‘xxx’ + ${collect.id}”/>
th:text 文本替换 < p th:text=”${collect.description}”>description< /p>
th:utext 支持html的文本替换 < p th:utext=”${htmlcontent}”>conten< /p>
th:object 替换对象 < div th:object=”${session.user}”>
th:value 属性赋值 < input th:value=”${user.name}” />
th:with 变量赋值运算 < div th:with=”isEven=${prodStat.count}%2==0”>< /div>
th:style 设置样式 th:style=”‘display:’ + @{(${sitrue} ? ‘none’ : ‘inline-block’)} + ‘’”
th:onclick 点击事件 th:”‘getCollect()’”
th:each 属性赋值 tr th:each=”user,userStat:${users}”>
th:if 判断条件 < a th:if=”${userId == collect.userId}” >
th:unless 和th:if判断相反 < a th:href=”@{/login}” th:unless=${session.user != null}>Login< /a>
th:href 链接地址 <a th:href=”@{/login}” th:unless=${session.user != null}>Login< /a>
th:switch 多路选择 配合th:case 使用 < div th:switch=”${user.role}”>
th:case th:switch的一个分支 < p th:case=”‘admin’”>User is an administrator< /p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 < div th:fragment=”alert”>
th:include 布局标签,替换内容到引入的文件 < head th:include=”layout :: htmlhead” th:with=”title=’xx’”>< /head>
th:replace 布局标签,替换整个标签到引入的文件 < div th:replace=”fragments/header :: title”>< /div>
th:selected selected选择框 选中 th:selected=”(${xxx.id} == ${configObj.dd})”
th:src 图片类地址引入 < img class=”img-responsive” alt=”App Logo” th:src=”@{/img/logo.png}” />
th:inline 定义js脚本可以使用变量 < script type=”text/javascript” th:inline=”javascript”>
th:action 表单提交的地址 < form action=”subscribe.html” th:action=”@{/subscribe}”>
th:remove 删除某个属性 < tr th:remove=”all”>1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。
th:attr 设置标签属性,多个属性可以用逗号分隔 比如 < p th:attr=”src=@{/image/aa.jpg},title=${title}”>内容< /p>,这样如果${title}=‘这个是title’ 则结果就是< p src=”/image/aa.jpg” title=”这个是title”>内容< /p>
文章作者:
文章链接: https://huohuohuohuohuohuo.github.io/2020/02/25/Thymeleaf-模板引擎/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论