Thymeleaf使用教程
Thymeleaf介绍
- Thymeleaf是一种用于Web和独立环境的现代服务器端的Java模板引擎。
- Thymeleaf的主要目标是将优雅的自然模板带到开发工作流程中,并将HTML在浏览器中正确显示,并且可以作为静态原型,让开发团队能更容易地协作。Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。
- Thymeleaf使用Spring框架的模块,与许多常见的工具集成在一起,并且可以插入自己的功能,是现代HTML5 JVM Web开发的理想选择,尽管Thymeleaf还有更多其它的功能。
- Thymeleaf建立在自然模板的概念之上,以不影响模板作为设计原型的方式将其逻辑注入到模板文件中。 这改善了设计沟通,弥合了前端设计和开发人员之间的理解偏差。
- Thymeleaf是一个非常容易扩展的模板引擎(事实上,它可以被称为模板引擎框架)。
Thymeleaf语法
变量表达式 ${}
- 使用方法:直接使用th:xx = “${}” 获取对象属性 。
- 例如
<td th:title="${activityCureProductVo.address}"></td>
<td th:text="${activityCureProductVo.state}"></td>
选择变量表达式 *{}
- 使用方法:首先通过 th:object获取对象,然后使用 th:xx = "*{}"获取对象属性。
- 例如
<form id="userForm" th:object="${user}">
<input id="id" name="id" th:value="*{id}"/>
<input id="username" name="username" th:value="*{username}"/>
<input id="password" name="password" th:value="*{password}"/>
</form>
链接表达式 @{}
- 使用方法:通过链接表达式**@{}**直接拿到应用路径,然后拼接静态资源路径。
- 例如
th:action="@{/font/fontIndex/women/{id}(id=${doctorActivityTypeList3.id})}"//后面id为通过链接传递id的值
片段表达式 ~{}
- 分为三种:
~{ viewName } 表示引入完整页面
~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
~{ ::selector} 表示在当前页寻找 - 使用方法:先通过th:fragment指定哪段代码为片段 ,然后通过th:replace 填写片段路径和片段名。
- 例如
<div class="o-container" th:fragment="footer"></div>
<footer class="c-footer" th:replace="font/_footer :: footer"></footer>
- 注意:使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/)。
消息表达式
- 即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。
- 例如
<title th:text="#{user.title}"></title>
其它表达式
- 在基础语法中,默认支持字符串连接、数学运算、布尔逻辑和三目运算等。
- 例如
<input name="name" th:value="${'I am '+(user.name!=null?user.name:'NoBody')}"/>
Thymeleaf对象
基础对象
- ctx :上下文对象。
- vars :上下文变量。
- locale:上下文的语言环境。
- request:(仅在web上下文)的 HttpServletRequest 对象。
- response:(仅在web上下文)的 HttpServletResponse 对象。
- session:(仅在web上下文)的 HttpSession 对象。
- servletContext:(仅在web上下文)的ServletContext 对象
这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。
// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"
常用的工具类
- #strings:字符串工具类:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
- #lists:List 工具类 和 #sets:Set 工具类:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
- #arrays:数组工具类:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
- #maps:常用Map方法:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
- #objects:一般对象类,通常用来判断非空
- #bools:常用的布尔方法,常用的方法有:isTrue,isFalse等
- #execInfo:获取页面模板的处理信息。
- #messages:在变量表达式中获取外部消息的方法,与使用#{…}语法获取的方法相同。
- #uris:转义部分URL / URI的方法。
- #conversions:用于执行已配置的转换服务的方法。
- #dates:时间操作和时间格式化等,常用的方法有:format,year,month,hour,createNow等。
- #calendars:用于更复杂时间的格式化。
- #numbers:格式化数字对象的方法,常用的方法有:formatDecimal等。
- #aggregates:在数组或集合上创建聚合的方法。
- #ids:处理可能重复的id属性的方法。
统一举例说明
<h3>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
<p>Old Str : <span th:text="${itdragonStr}"/></p>
<p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
<p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
<p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
<p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
<p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
<p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
<p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
<p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
<p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>
<h3>#lists </h3>
<div th:if="${not #lists.isEmpty(itdragonList)}">
<p>size : <span th:text="${#lists.size(itdragonList)}"/></p>
<p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p>
<p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p>
</div>
<h3>#arrays </h3>
<div th:if="${not #arrays.isEmpty(itdragonArray)}">
<p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p>
<p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p>
<p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p>
</div>
<h3>#maps </h3>
<div th:if="${not #maps.isEmpty(itdragonMap)}">
<p>size : <span th:text="${#maps.size(itdragonMap)}"/></p>
<p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p>
<p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p>
</div>
<h3>#bools </h3>
<div th:if="${#bools.isTrue(itdragonBool)}">
<p th:text="${itdragonBool}"></p>
</div>
<h3>#dates </h3>
<div>
<p>format : <span th:text="${#dates.format(itdragonDate)}"/></p>
<p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
<p>day : <span th:text="${#dates.day(itdragonDate)}"/></p>
<p>month : <span th:text="${#dates.month(itdragonDate)}"/></p>
<p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p>
<p>year : <span th:text="${#dates.year(itdragonDate)}"/></p>
<p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p>
<p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p>
<p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p>
<p>second : <span th:text="${#dates.second(itdragonDate)}"/></p>
<p>createNow : <span th:text="${#dates.createNow()}"/></p>
</div>
<h3>#numbers </h3>
<div>
<p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p>
<p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p>
</div>
Thymeleaf方法
遍历
- 想要遍历List集合很简单,配合th:each 即可快速完成迭代。例如:
<tr th:each="aa:${pageInfo.list}">
<td><input type="checkbox" value="1" th:value="${aa.activityId}" name="id"/></td>
<td th:text="${aa.startTime}"></td>
<td th:text="${aa.endTime}"></td>
</th>
- 在集合的迭代过程还可以获取状态变量,只需在变量后面指定状态变量名即可,状态变量可用于获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。例如:
<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>
条件判断
- 条件判断通常用于动态页面的初始化,例如:
<div th:if="${userList}">
<div>的确存在..</div>
</div>
- 如果想取反则使用unless 例如:
<div th:unless="${userList}">
<div>不存在..</div>
</div>
日期格式化
- 使用默认的日期格式(toString方法) 得到的格式:2018-12-03 T 23:16:50。此时可以通过时间工具类#dates来对日期进行格式化
- 例如
<td th:text="${#temporals.format(aa.updateTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
结果为:2018-12-03 23:16:50
内联写法
- 标准格式为:[[${xx}]] ,可以读取服务端变量,也可以调用内置对象的方法。
- 内联表达式仅在页面生效,不能再js中使用,因为Thymeleaf只负责解析一级视图,不能识别外部标签JS里面的表达式。
页面显示和国际化
- 例如在国际化文件中编写了user.title这个键值,然后使用#{}读取这个KEY即可获取翻译。
<title th:text="#{user.title}">用户登陆</title>
- 需要详细了解请点击