thymeleaf模板引擎常用语法总览

官网文档:https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#the-template-engine

1、引入thymeleaf

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

2、变量表达试

基于java变量

<p th:text="${msg}">显示信息</p>
<p th:text="${user.name}">显示姓名</p>

3、选择变量表达式

 <div th:object="${user}">
      <p th:text="*{name}">姓名</p>
      <p th:text="*{age}">年龄</p>
      <p th:text="*{age}">性别</p>
</div>

4、URL表达式

<script th:src="@{/webjars/jquery/jquery.js}"></script>
<link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">
<a th:href="@{/login}">登录</a>
<a th:href="@{/index?a=21&b=${tid}|}" >查看标签</a>

<div th:style="'background:url(' + @{${img}} + ');'">
<div class="media-object resource-card-image"  th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>

`

5、常用内置对象

  • #ctx:访问上下文对象。
  • #vars:访问上下文中的所有变量。
  • #locale:访问当前区域设置。
  • #httpServletRequest:访问HttpServletRequest对象。
  • #httpSession:访问HttpSession对象。

6、常用内置方法

  • #strings:字符串处理方法,如#strings.toUpperCase(str)
  • #dates:日期处理方法,如#dates.format(date, 'yyyy-MM-dd')
  • #lists:集合处理方法,如#lists.size(list)
  • #arrays 数组函数
  • #numbers 数字函数
  • #calendars 日历函数
  • #objects 对象函数
  • #bools 布尔函数

7、消息表达式

即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。例如:

<title th:text="#{user.title}"></title>

8、片段表达式

  • ~{viewName} 表示引入完整页面
  • ~{viewName::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
  • ~{::selector} 表示在当前页寻找
<!-- /views/common/head.html-->
<head th:fragment="static">
        <script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>

<!-- /views/your.html -->
<div th:replace="~{common/head::static}"></div>

简写:

<!-- your.html -->
<div th:replace="common/head::static"></div>

注意:使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/

9、条件判断

<div th:if="${user.age} > 18">成年用户</div>

<div th:unless="${userList}">
  <div>不存在..</div>
</div>
  • gt(>):great than(⼤于)
  • lt(<):less than (⼩于)
  • ge(>=):great equal(⼤于等于)
  • le(<=):less equal(⼩于等于)
  • not(!):not(否定)
  • eq(==):equal(等于)
  • neq/ne(!=):not equal(不等于)

10、switch分支

<div th:switch="${user.role}">
    <p th:case="'admin'">管理员</p>
    <p th:case="'user'">普通用户</p>
    <p th:case="*">未知角色</p>
</div>

11、数据遍历

<ul>
    <li th:each="item : ${items}" th:text="${item.name}">默认列表项</li>
</ul>

获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。

<div th:each="user,stat:${userList}" th:class="${stat.even}?'even':'odd'">
  下标:<input th:value="${stat.index}"/>
  序号:<input th:value="${stat.count}"/>
  账号:<input th:value="${user.username}"/>
  密码:<input th:value="${user.password}"/>
</div>

`

如果缺省状态变量名,则迭代器会默认帮我们生成以变量名开头的状态变量 xxStat, 例如:

<div th:each="user:${userList}" th:class="${userStat.even}?'even':'odd'">
  下标:<input th:value="${userStat.index}"/>
  序号:<input th:value="${userStat.count}"/>
  账号:<input th:value="${user.username}"/>
  密码:<input th:value="${user.password}"/>
</div>
  • index:当前迭代对象的 index(从 0 开始计算)
  • count:当前迭代对象的 index(从 1 开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从 0 开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

12、逻辑运算符

<p th:text="${user.age} + 1">年龄加一</p>

<p th:text="${user.age} > 18 and ${user.gender} == 'male'">成年男性</p>

13、内联

[[..]][(...)] 之间的表达式在 Thymeleaf 模板中称之为内联表达式,这相当于在 HTML 标签中分别使用 th:textth:utext 来设置对应的元素的文本值,其使用方式如下:

<!--表达式内联-->
<!--对应表达式的值按照文本进行处理,不会处理HTML标签效果-->
<li><span>表达式内联:</span>公众号名称是[[${gzh}]]</li>

<!--对应表达式的值按照不按文本进行处理,会处理带HTML标签效果-->
<li><span>表达式内联:</span>公众号名称是[(${gzh})]</li>

JavaScript 内联允许在 js 代码中直接使用 [[${...}]] 获取里面表达式的值,使用时需要在 <script> 模块使用 th:inline="javascript" 开启 javascript 内联支持,使用方式如下:

<script th:inline="javascript">
    function gzhName() {
        // 输出未转义的字符
        // let gzh = [(${gzh})];
        // js获取后端传入的名称为gzh的值
        let gzh = [[${gzh}]];
        console.log("gzhName:" + gzh);
        let span = document.getElementsByClassName("jsInline");
        span[0].innerHTML = gzh.toString();
    }
</script>

<!--javascript内联-->
<li><span>javascript内联:</span><button onclick="gzhName()">从js获取变量值</button><span class="jsInline"></span></li>

CSS 内联允许在 <style> 中直接使用 [[${...}]] 获取里面表达式的值,使用时需要在 <style> 中使用 th:inline="css" 开启 CSS 内联支持,使用方式如下:

<!--开启CSS内联-->
<style th:inline="css">
    /*设置idName对应id的元素内字体的颜色*/
    #[[${idName}]]{
        /*CSS自然模板*/
        color:/*[(${color})]*/ #0000FF;
    }
</style>

<!--CSS内联-->
<li><span>CSS内联:</span><span id="css">测试CSS内联</span></li>

14、字符串拼接

<span th:text="'我的字符串数据:'+${msg}">数据信息</span>

简写方式:

<span th:text="|我的字符串数据:${msg}|">数据信息</span>

15、其他表达式

一般用于表单控件

<input name="name" th:value="${'I am '+(user.name!=null?user.name:'NoBody')}"/>

16、日期格式化

<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>

17、fragment包含替换

创建模板:

<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1">
    <p>All Rights Reserved</p>
</footer>

<footer th:fragment="footer2(start,now)">
    <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>

使用:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <title>Thymeleaf快速入门-Hello Thymeleaf</title>
</head>
<body>
  <div th:include="include::footer1"></div>
  <div th:replace="include::footer2(2015,2018)"></div>
</body>
</html>
  • th:insert 当前标签里面插入模板中的标签
  • th:replace 替换当前标签为模板中的标签
  • th:include 当前标签里面插入模板的标签内容

18、常用标签

  • th:action 定义服务器端控制器路径。
  • th:each 循环语句
  • th:field 表单字段
  • th:href URL 链接
  • th:id div 标签中的 ID
  • th:if 条件判断
  • th:include 引入文件
  • th:fragment 定义代码片段
  • th:object 替换对象
  • th:src 图片地址
  • th:text 文本
  • th:value 属性值

19、block块

th:block 是一个虚拟元素,用于分组和逻辑控制,而不会在最终的 HTML 输出中生成任何实际的标签。

可以用来包裹多个元素,以便在逻辑判断中一起处理。

<th:block th:if="${condition}">
    <p>This will be displayed if the condition is true.</p>
    <div>Additional content here.</div>
</th:block>

用于定义模板片段。

<th:block th:fragment="myFragment">
    <p>This is a reusable fragment.</p>
</th:block>

可以组合多个属性应用于一组元素。

<th:block th:each="item : ${items}">
    <p th:text="${item.name}"></p>
    <span th:text="${item.value}"></span>
</th:block>
PS:写作不易,如要转裁,请标明转载出处。
%{ comment.page.total }条评论

猜你想看

微信小程序:前端开发宝典

最近文章
工具操作
  • 内容截图
  • 全屏
登录
注册
回顶部