理解Thymeleaf
- Java模版引擎:Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。能够处理HTML、XML、JavaScript、CSS甚至纯文本。
- 自然模板:Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板——HTML,它可以在浏览器中正确显示,也可以作为静态原型工作(原型即界面),改善了设计与开发的沟通,从而在开发团队中实现更强的协作。
<table> <thead> <tr> <th th:text="#{msgs.headers.name}">Name</th> <th th:text="#{msgs.headers.price}">Price</th> </tr> </thead> <tbody> <tr th:each="prod: ${allProducts}"> <td th:text="${prod.name}">Oranges</td> <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td> </tr> </tbody> </table>
- 语法优雅易懂:
- 遵从web标准,支持HTML5
Thymeleaf 使用
一、标准方言
秉着“开箱即用”的原则,Thymeleaf提供了满足大多数情况下的默认实现-标准方言(后面会介绍自定义方言):
- 引入标签库(命名空间),常用的一种方式:
<span th:text="">....</span>
需要引入命名空间<html xmlns:th="http://www.thymeleaf.org">
- HTML5标准,自定义属性:
<span data-th-text="">.....</span>
<table> <tr data-th-each="user : ${users}"> <td data-th-text="${user.login}">...</td> <td data-th-text="${user.name}">...</td> </tr> </table>
这样可以省去命名空间
Thymeleaf基本语法
标准表达式
变量表达式
- 语法:${...}
- 用法:
<p th:text="${book.author}"></p>
消息表达式
- 语法:#{...}
- 用法:
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
相当于消息的一个key,也称文本外部化,一般用于国际化等外部配置文件,其中properties文件内容为home.welcome=welcome to thymeleaf
目前消息文件中的内容是固定的,如果我们需要向消息中动态插入一个参数以便实现动态消息,可以#{messageKey(param=value)},多个参数用,分割-#{messageKey(param1=value1, param2=value2)},messageKey本身也可以是一个变量表达式:
home.welcome=welcome to {0}
<p th:utext="#{home.welcome(${session.user.name})}"> Welcome to our grocery store, Sebastian Pepper! </p> <p th:utext="#{${welcomeMsgKey}(${session.user.name})}"> Welcome to our grocery store, Sebastian Pepper! </p>
- 消息源
大多数情况下, 消息源是.properties文件,同时可以自定义其他消息源,比如数据库。消息源通过org.thymeleaf.messageresolver.IMessageResolver获取,如果在初始化模板引擎时没有自定义的IMessageResolver被提供,那么一个默认的实现org.thymeleaf.messageresolver.StandardMessageResolver会被自动提供。
StandardMessageResolver查找和模板文件位于同级目录,且具有和模板文件相同名字的.properties文件。
模板/templates/home.html在渲染时,会根据local设置,使用下面的消息源文件
- /templates/home_zh_CN.properties --->中文
- /templates/home_en.properties --->英文
- /templates/home.properties 如--->特定的lcoal不可用时使用
在spring boot中,默认去寻找resources下面名为messages的properties文件,可以通过spring.messages.basename进行修改
选择表达式
- 语法:*{...}
- 示例:
<div th:object="${session.book}"> <p>Name: <span th:text="*{title}">thymeleaf实战</span>.</p> <p>Surname: <span th:text="*{author}">Peppa</span>.</p> <p>Nationality: <span th:text="*{price}">300</span>.</p> </div>
与变量表达式的区别:它们是在当前选择的对象而不是整个上下文变量映射上执行(性能高)
链接表达式
- 语法:@{...}
- 示例
- 绝对url:
<a th:href="@{http://www.thymeleaf.org}" th:text="">...</>
- 相对url,可以是:
- 相对url: user/login.html
- 上下文相对:
/itemdetails?id=3
(自动添加服务器中的应用上下文名称) - 服务器相对:
~/billing/processInvoice
(允许在同一服务器的另一个上下文(=应用程序)中调用URL). - 协议相对:
//code.jquery.com/jquery-2.0.3.min.js
eg:
在链接中使用参数(变量)
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
多个参数:
<a href="details.html" th:href="@{/order/details(orderId=${o.id},orderType=${o.type})}">view</a>
RESTful风格:
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${orderId})}">view</a>
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
多个参数:
<a href="details.html" th:href="@{/order/details(orderId=${o.id},orderType=${o.type})}">view</a>
RESTful风格:
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${orderId})}">view</a>
片段表达式
片段表达式是表示标记片段并围绕模板移动它们的简单方法。这允许我们复制它们,将它们作为参数传递给其他模板,等等
- 语法:~{...}
- 示例:
<div th:align="center" th:fragment="footer"> .... </div>
定义片段<div th:insert="~{commons :: footer}">...</div>
使用th:insert or th:replace插入片段,它们可以在任何地方使用,就像任何其他变量一样:<div th:with="frag=~{footer :: #footer/text()}"> <p th:insert="${frag}"> </div>
Thymeleaf基本语法
字面量
- 文本字面量:
'one text'
,'Another one!'
,… -
<p th:text="'<h1>我是一个香蕉,蕉蕉蕉蕉蕉蕉</h1>'"</p> <p th:utext="'<h1>我是一个香蕉,蕉蕉蕉蕉蕉蕉</h1>'"</p> 区别:th:text对html标签转义,th:utext不转义,解析为html内容
- 数字字面量:
0
,34
,3.0
,12.3
,… - Boolean 字面量:
true
,false
- Null 值字面量:
null
- 文字标记:
one
,sometext
,main
,…(不需要单引号'',这些令牌允许在标准表达式中进行一点简化。它们的工作与文本文字('...'
)完全相同,但它们只允许使用字母(A-Z
和a-z
),数字(0-9
),括号([
和]
),点(.
),连字符(-
)和下划线(_
)。所以没有空白,没有逗号等) - 文本操作:
- 字符串连接:
+
- 文字替换:
|The name is ${name}|
- 字符串连接:
- 算术运算符:
- 二元运算符:
+
,-
,*
,/
,%
- 减号(一元运算):
-
- 二元运算符:
- 逻辑运算符:
- 二元运算符:
and
,or
- 逻辑非(一元运算符):
!
,not
- 二元运算符:
- 比较运算符:
- 比较运算符:
>
,<
,>=
,<=
(gt
,lt
,ge
,le
) - 相等比较:
==
,!=
(eq
,ne
)
- 比较运算符:
- 条件运算符:
- If-then:
(if) ? (then)
- If-then-else:
(if) ? (then) : (else)
- Default:
(value) ?: (defaultvalue)
- If-then:
- Special tokens:
- No-Operation(无操作):
_
如果条件不满足,保留在原型中定义的值(文本)
- No-Operation(无操作):
<p th:utext="${user.username}?:_">我是原型的值</p>
设置属性值
- Java模版引擎:Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。能够处理
- 设置任意属性值-->th:attr
<form action="subscribe.html" th:attr="action=@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form>
- 设置值到指定的属性---->HTML5标签的常用属性。如:
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/> <form action="subscribe.html" th:action="@{/subscribe}"> <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>
- 固定值布尔属性---->属性就代表值
<input type="checkbox" name="active" th:checked="${user.active}" />
-
迭代器
- 基本的迭代---->th:each
<li th:each="book:${books}" th:text="${book.title}"></li>
- ${books}为迭代变量(作用域中的
Iterable,
Enumeration,
Iterator,Map,Entry,Array及字符串等,相当于标准标签库中<c:forEach>里的items属性);
- book为当前迭代的元素,相当于var属性
- ${books}为迭代变量(作用域中的
- 状态变量:跟踪迭代器的状态(相当于标准标签库的varStatus标签)
<table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> </tr> <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr> </table>
- index:当前迭代索引,从0开始。
- count:当前迭代索引,从1开始。
- size:迭代变量中元素的总数。
- current:每个迭代的ITER变量。
- even/odd:当前迭代是偶数还是奇数。
- first:当前迭代是否为第一个元素。
- last:当前迭代是否为最后一个元素。
-
条件语句
- th:if
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
- th:unless---->条件不成立
<a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a>
- th:switch/th:case
<div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </div>
-
模板布局
- 在我们的模板中,我们通常希望包括来自其他模板的部件,如页脚、页眉、菜单等部件(公共部分);或是固定的模板格式渲染成不同的内容,如邮件模板,商品详情页模板…
为了做到这一点,thymeleaf需要我们定义这些部分,“片段”,以便包含,这可以使用th:fragment属性完成。
假设我们想在所有杂货店页面中添加一个标准的版权页脚,那么我们创建一个/templates/footer.html文件,其中包含以下代码:<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> </body> </html>
使用th:insert或者th:replace插入片段,th:include只插入片段内容(不推荐使用)<body> ... <div th:insert="~{footer :: copy}"></div> </body>
其中footer为模板名称,copy为片段名称,也可以不使用th:fragment,使用格式如下<div id="copy-section"> © 2011 The Good Thymes Virtual Grocery </div> ... <body> ... <div th:insert="~{footer :: #copy-section}"></div> </body>
-
注释
- 标准html/xml注释
- thymeleaf解析器级注释
<!--/* <div th:text="${...}"> ... </div> */-->
- 原型注释块[静态时注释,模板执行时显示
<!--/*/ <div th:text="${...}"> ... </div> /*/-->
-
内联
- 直接将表达式写在文本中而非标签中,js,css中使用常见
<script th:inline="javascript"> ... var username = [[${session.user.name}]]; ... </script>
- 格式:[[...]]或者[(...)]分别对应th:text和th:utext
- 禁用内联---->th:inline="none"
-
表达式基本对象(隐式对象,存在于上下文中)
-
#ctx:上下文对象
/* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IContext * ====================================================================== */ ${#ctx.locale} ${#ctx.variableNames} /* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IWebContext * ====================================================================== */ ${#ctx.request} ${#ctx.response} ${#ctx.session} ${#ctx.servletContext}
-
#locale:直接访问与java.util.Locale关联的当前请求
${#locale}
-
param,获取请求相关的属性,如请求参数,request.getParmeter("")等
/* * ============================================================================ * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap * ============================================================================ */ ${param.foo} //request.getParameterValues("foo") ${param.size()} ${param.isEmpty()} ${param.containsKey('foo')} ...
-
session : for retrieving session attributes.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap * ====================================================================== */ ${session.foo} // session.getAtttribute('foo') ${session.size()} ${session.isEmpty()} ${session.containsKey('foo')} ...
-
application : for retrieving application/servlet context attributes.
/* * ============================================================================= * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap * ============================================================================= */ ${application.foo} //servletContext.getAtttribute('foo') ${application.size()} ${application.isEmpty()} ${application.containsKey('foo')} ...
${myRequestAttribute}
- Web 上下文对象
-
#request : 当前请求
javax.servlet.http.HttpServletRequest
.${#request.getAttribute('foo')} ${#request.getParameter('foo')} ${#request.getContextPath()} ${#request.getRequestName()} ...
-
#session :
javax.servlet.http.HttpSession
${#session.getAttribute('foo')} ${#session.id} ${#session.lastAccessedTime} ...
-
#servletContext :
javax.servlet.ServletContext
${#servletContext.getAttribute('foo')} ${#servletContext.contextPath} ...
-
#request : 当前请求
-
块
- 标准方言中包含的thymeleaf的唯一元素处理器(不是属性)是th:block。
th:block是一个属性容器,允许模板开发人员指定他们想要的属性。thymeleaf将执行这些属性,然后简单地使块(而不是其内容)消失。
因此,它可能很有用,例如,当创建迭代表时,每个元素需要一个以上的<tr>,或者需要条件判断时<table> <th:block th:each="user : ${users}"> <tr> <td th:text="${user.login}">...</td> <td th:text="${user.name}">...</td> </tr> <tr> <td colspan="2" th:text="${user.address}">...</td> </tr> </th:block> </table>
实用对象
这些使用表达式对象在package org.thymeleaf.expression包下都有对应的类,如果不知道怎么使用直接看Javadoc就好,推荐使用的时候按需查询。
Messages
- #messages : 用于在变量表达式中获得外部消息的实用方法,与使用#{…}语法获得的方式相同.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Messages * ====================================================================== */ ${#messages.msg('msgKey')} ${#messages.msg('msgKey', param1)} ${#messages.msg('msgKey', param1, param2)} ${#messages.msg('msgKey', param1, param2, param3)} ${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})} ${#messages.arrayMsg(messageKeyArray)} ${#messages.listMsg(messageKeyList)} ${#messages.setMsg(messageKeySet)} ${#messages.msgOrNull('msgKey')} ${#messages.msgOrNull('msgKey', param1)} ${#messages.msgOrNull('msgKey', param1, param2)} ${#messages.msgOrNull('msgKey', param1, param2, param3)} ${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})} ${#messages.arrayMsgOrNull(messageKeyArray)} ${#messages.listMsgOrNull(messageKeyList)} ${#messages.setMsgOrNull(messageKeySet)}
URIs/URLs
- #uris : 用于在Thymeleaf标准表达式中执行URI / URL操作(特别是转义/消除转义)的实用对象.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Uris * ====================================================================== */ /* * Escape/Unescape as a URI/URL path */ ${#uris.escapePath(uri)} ${#uris.escapePath(uri, encoding)} ${#uris.unescapePath(uri)} ${#uris.unescapePath(uri, encoding)} /* * Escape/Unescape as a URI/URL path segment (between '/' symbols) */ ${#uris.escapePathSegment(uri)} ${#uris.escapePathSegment(uri, encoding)} ${#uris.unescapePathSegment(uri)} ${#uris.unescapePathSegment(uri, encoding)} /* * Escape/Unescape as a Fragment Identifier (#frag) */ ${#uris.escapeFragmentId(uri)} ${#uris.escapeFragmentId(uri, encoding)} ${#uris.unescapeFragmentId(uri)} ${#uris.unescapeFragmentId(uri, encoding)} /* * Escape/Unescape as a Query Parameter (?var=value) */ ${#uris.escapeQueryParam(uri)} ${#uris.escapeQueryParam(uri, encoding)} ${#uris.unescapeQueryParam(uri)} ${#uris.unescapeQueryParam(uri, encoding)}
Conversions
- #conversions : 允许在模板的任意位置执行转换服务的实用程序对象:
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Conversions * ====================================================================== */ /* * Execute the desired conversion of the 'object' value into the * specified class. */ ${#conversions.convert(object, 'java.util.TimeZone')} ${#conversions.convert(object, targetClass)}
Dates
- #dates : 为 java.util.Date对象提供工具方法,比如:格式化,提取年月日等:
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Dates * ====================================================================== */ ${#dates.format(date)} ${#dates.arrayFormat(datesArray)} ${#dates.listFormat(datesList)} ${#dates.setFormat(datesSet)} ${#dates.formatISO(date)} ${#dates.arrayFormatISO(datesArray)} ${#dates.listFormatISO(datesList)} ${#dates.setFormatISO(datesSet)} ${#dates.format(date, 'dd/MMM/yyyy HH:mm')} ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')} ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')} ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')} ${#dates.day(date)} // also arrayDay(...), listDay(...), etc. ${#dates.month(date)} // also arrayMonth(...), listMonth(...), etc. ${#dates.monthName(date)} // also arrayMonthName(...), listMonthName(...), etc. ${#dates.monthNameShort(date)} // also arrayMonthNameShort(...), listMonthNameShort(...), etc. ${#dates.year(date)} // also arrayYear(...), listYear(...), etc. ${#dates.dayOfWeek(date)} // also arrayDayOfWeek(...), listDayOfWeek(...), etc. ${#dates.dayOfWeekName(date)} // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc. ${#dates.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc. ${#dates.hour(date)} // also arrayHour(...), listHour(...), etc. ${#dates.minute(date)} // also arrayMinute(...), listMinute(...), etc. ${#dates.second(date)} // also arraySecond(...), listSecond(...), etc. ${#dates.millisecond(date)} // also arrayMillisecond(...), listMillisecond(...), etc. /* * Create date (java.util.Date) objects from its components */ ${#dates.create(year,month,day)} ${#dates.create(year,month,day,hour,minute)} ${#dates.create(year,month,day,hour,minute,second)} ${#dates.create(year,month,day,hour,minute,second,millisecond)} /* * Create a date (java.util.Date) object for the current date and time */ ${#dates.createNow()} ${#dates.createNowForTimeZone()} /* * Create a date (java.util.Date) object for the current date (time set to 00:00) */ ${#dates.createToday()} ${#dates.createTodayForTimeZone()}
Calendars
- #calendars : 类似于#dates , 但是只针对java.util.Calendar对象:
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Calendars * ====================================================================== */ /* * Format calendar with the standard locale format * Also works with arrays, lists or sets */ ${#calendars.format(cal)} ${#calendars.arrayFormat(calArray)} ${#calendars.listFormat(calList)} ${#calendars.setFormat(calSet)} /* * Format calendar with the ISO8601 format * Also works with arrays, lists or sets */ ${#calendars.formatISO(cal)} ${#calendars.arrayFormatISO(calArray)} ${#calendars.listFormatISO(calList)} ${#calendars.setFormatISO(calSet)} /* * Format calendar with the specified pattern * Also works with arrays, lists or sets */ ${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')} ${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')} ${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')} ${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')} /* * Obtain calendar properties * Also works with arrays, lists or sets */ ${#calendars.day(date)} // also arrayDay(...), listDay(...), etc. ${#calendars.month(date)} // also arrayMonth(...), listMonth(...), etc. ${#calendars.monthName(date)} // also arrayMonthName(...), listMonthName(...), etc. ${#calendars.monthNameShort(date)} // also arrayMonthNameShort(...), listMonthNameShort(...), etc. ${#calendars.year(date)} // also arrayYear(...), listYear(...), etc. ${#calendars.dayOfWeek(date)} // also arrayDayOfWeek(...), listDayOfWeek(...), etc. ${#calendars.dayOfWeekName(date)} // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc. ${#calendars.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc. ${#calendars.hour(date)} // also arrayHour(...), listHour(...), etc. ${#calendars.minute(date)} // also arrayMinute(...), listMinute(...), etc. ${#calendars.second(date)} // also arraySecond(...), listSecond(...), etc. ${#calendars.millisecond(date)} // also arrayMillisecond(...), listMillisecond(...), etc. /* * Create calendar (java.util.Calendar) objects from its components */ ${#calendars.create(year,month,day)} ${#calendars.create(year,month,day,hour,minute)} ${#calendars.create(year,month,day,hour,minute,second)} ${#calendars.create(year,month,day,hour,minute,second,millisecond)} ${#calendars.createForTimeZone(year,month,day,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)} ${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)} /* * Create a calendar (java.util.Calendar) object for the current date and time */ ${#calendars.createNow()} ${#calendars.createNowForTimeZone()} /* * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00) */ ${#calendars.createToday()} ${#calendars.createTodayForTimeZone()}
Numbers
- #numbers : 为数值型对象提供工具方法:
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Numbers * ====================================================================== */ /* * ========================== * Formatting integer numbers * ========================== */ /* * Set minimum integer digits. * Also works with arrays, lists or sets */ ${#numbers.formatInteger(num,3)} ${#numbers.arrayFormatInteger(numArray,3)} ${#numbers.listFormatInteger(numList,3)} ${#numbers.setFormatInteger(numSet,3)} /* * Set minimum integer digits and thousands separator: * 'POINT', 'COMMA', 'WHITESPACE', 'NONE' or 'DEFAULT' (by locale). * Also works with arrays, lists or sets */ ${#numbers.formatInteger(num,3,'POINT')} ${#numbers.arrayFormatInteger(numArray,3,'POINT')} ${#numbers.listFormatInteger(numList,3,'POINT')} ${#numbers.setFormatInteger(numSet,3,'POINT')} /* * ========================== * Formatting decimal numbers * ========================== */ /* * Set minimum integer digits and (exact) decimal digits. * Also works with arrays, lists or sets */ ${#numbers.formatDecimal(num,3,2)} ${#numbers.arrayFormatDecimal(numArray,3,2)} ${#numbers.listFormatDecimal(numList,3,2)} ${#numbers.setFormatDecimal(numSet,3,2)} /* * Set minimum integer digits and (exact) decimal digits, and also decimal separator. * Also works with arrays, lists or sets */ ${#numbers.formatDecimal(num,3,2,'COMMA')} ${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')} ${#numbers.listFormatDecimal(numList,3,2,'COMMA')} ${#numbers.setFormatDecimal(numSet,3,2,'COMMA')} /* * Set minimum integer digits and (exact) decimal digits, and also thousands and * decimal separator. * Also works with arrays, lists or sets */ ${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')} ${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')} ${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')} ${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')} /* * ===================== * Formatting currencies * ===================== */ ${#numbers.formatCurrency(num)} ${#numbers.arrayFormatCurrency(numArray)} ${#numbers.listFormatCurrency(numList)} ${#numbers.setFormatCurrency(numSet)} /* * ====================== * Formatting percentages * ====================== */ ${#numbers.formatPercent(num)} ${#numbers.arrayFormatPercent(numArray)} ${#numbers.listFormatPercent(numList)} ${#numbers.setFormatPercent(numSet)} /* * Set minimum integer digits and (exact) decimal digits. */ ${#numbers.formatPercent(num, 3, 2)} ${#numbers.arrayFormatPercent(numArray, 3, 2)} ${#numbers.listFormatPercent(numList, 3, 2)} ${#numbers.setFormatPercent(numSet, 3, 2)} /* * =============== * Utility methods * =============== */ /* * Create a sequence (array) of integer numbers going * from x to y */ ${#numbers.sequence(from,to)} ${#numbers.sequence(from,to,step)}
Strings
- #strings : 为String 对象提供工具方法。如: contains, startsWith, prepending/appending等:
Objects
- #objects : 为object 对象提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Objects * ====================================================================== */ /* * Return obj if it is not null, and default otherwise * Also works with arrays, lists or sets */ ${#objects.nullSafe(obj,default)} ${#objects.arrayNullSafe(objArray,default)} ${#objects.listNullSafe(objList,default)} ${#objects.setNullSafe(objSet,default)}
Booleans
- #bools : 为boolean 对象提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Bools * ====================================================================== */
Arrays
- #arrays : 为arrays 对象提供常用的工具方法;
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Arrays * ====================================================================== */ /* * Converts to array, trying to infer array component class. * Note that if resulting array is empty, or if the elements * of the target object are not all of the same class, * this method will return Object[]. */ ${#arrays.toArray(object)} /* * Convert to arrays of the specified component class. */ ${#arrays.toStringArray(object)} ${#arrays.toIntegerArray(object)} ${#arrays.toLongArray(object)} ${#arrays.toDoubleArray(object)} ${#arrays.toFloatArray(object)} ${#arrays.toBooleanArray(object)} /* * Compute length */ ${#arrays.length(array)} /* * Check whether array is empty */ ${#arrays.isEmpty(array)} /* * Check if element or elements are contained in array */ ${#arrays.contains(array, element)} ${#arrays.containsAll(array, elements)}
Lists
- #lists :为lists对象提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Lists * ====================================================================== */ /* * Converts to list */ ${#lists.toList(object)} /* * Compute size */ ${#lists.size(list)} /* * Check whether list is empty */ ${#lists.isEmpty(list)} /* * Check if element or elements are contained in list */ ${#lists.contains(list, element)} ${#lists.containsAll(list, elements)} /* * Sort a copy of the given list. The members of the list must implement * comparable or you must define a comparator. */ ${#lists.sort(list)} ${#lists.sort(list, comparator)}
Sets
- #sets : 为lists对象提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Sets * ====================================================================== */ /* * Converts to set */ ${#sets.toSet(object)} /* * Compute size */ ${#sets.size(set)} /* * Check whether set is empty */ ${#sets.isEmpty(set)} /* * Check if element or elements are contained in set */ ${#sets.contains(set, element)} ${#sets.containsAll(set, elements)}
Maps
- #maps : 为lists对象提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Maps * ====================================================================== */ /* * Compute size */ ${#maps.size(map)} /* * Check whether map is empty */ ${#maps.isEmpty(map)} /* * Check if key/s or value/s are contained in maps */ ${#maps.containsKey(map, key)} ${#maps.containsAllKeys(map, keys)} ${#maps.containsValue(map, value)} ${#maps.containsAllValues(map, value)}
Aggregates
- #aggregates : 为创造一个arrays 或者 collections聚集函数提供常用的工具方法
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Aggregates * ====================================================================== */ /* * Compute sum. Returns null if array or collection is empty */ ${#aggregates.sum(array)} ${#aggregates.sum(collection)} /* * Compute average. Returns null if array or collection is empty */ ${#aggregates.avg(array)} ${#aggregates.avg(collection)}
IDs
- #ids :为可能需要循环的ID属性提供常用的工具方法.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Ids * ====================================================================== */ /* * Normally used in th:id attributes, for appending a counter to the id attribute value * so that it remains unique even when involved in an iteration process. */ ${#ids.seq('someId')} /* * Normally used in th:for attributes in <label> tags, so that these labels can refer to Ids * generated by means if the #ids.seq(...) function. * * Depending on whether the <label> goes before or after the element with the #ids.seq(...) * function, the "next" (label goes before "seq") or the "prev" function (label goes after * "seq") function should be called. */ ${#ids.next('someId')} ${#ids.prev('someId')}
- 下一章节介绍在spring mvc中使用以及在springboot中使用
相关推荐
Thymeleaf实战:探索现代Web开发中的模板引擎 Thymeleaf是一个强大的、现代的模板引擎,专门设计用于Web应用程序。与Velocity和FreeMarker等其他模板引擎相比,Thymeleaf提供了一些独特的特性和优势,使其在Java...
本文档详细记录了从零开始构建基于Java的简单Web应用程序全过程,重点介绍了使用Spring Boot框架与Thymeleaf进行前后端协作的设计思路,提供了具体的编码实现方法。主要涉及创建项目的文件结构、配置所需的Maven依赖...
Thymeleaf提供了对Spring 3.x和4.x版本的支持,通过名为thymeleaf-spring3和thymeleaf-spring4的两个独立库实现。这些库被打包为单独的.jar文件(thymeleaf-spring3-{version}.jar和thymeleaf-spring4-{version}.jar...
基于springboot+thymeleaf+spring data jpa+druid+bootstrap+layui等技术的JavaWeb电商项目(项目包含前后台,分为前台商城系统及后台管理系统。前台商城系统包含首页门户
在本项目实战中,我们将深入探讨Spring Boot与Thymeleaf的集成应用,这是一个流行的Java Web开发框架组合,用于快速构建高效、现代化的Web应用程序。Spring Boot简化了Spring的配置,而Thymeleaf则是一个功能强大的...
《Spring Boot 2+Thymeleaf企业应用实战》是杨恩雄编著的一本面向Java Web开发的技术书籍,这本书籍主要介绍了Spring Boot框架及其与Thymeleaf模板引擎的结合使用。内容覆盖了从Spring Boot和Spring MVC基础,到...
《SpringBoot与Thymeleaf实战教程:搭建项目与数据渲染》 在现代Web开发中,SpringBoot以其简洁、高效的特点成为了许多开发者的首选框架。而Thymeleaf作为一款强大的模板引擎,常用于SpringBoot项目中进行视图层的...
四、Thymeleaf实战应用 在"thymeleaf.zip"文件中,你可能看到的文件结构包括: - `templates`目录:存放HTML模板文件,如`index.html`,它可能包含上面提到的各种Thymeleaf语法。 - `src/main/java`目录:包含Spring...
在"spring-boot-thymeleaf"这个实战项目中,你可能会学习到如何创建SpringBoot工程,添加Thymeleaf依赖,配置Thymeleaf模板路径,编写Controller,设计HTML模板,以及如何处理用户输入和响应。通过实际操作,你可以...
5.15-5.16 5-15 -Thymeleaf实战-前后台编码 5.17-1.18 5-17 -Thymeleaf实战-前后台编码 第6章 数据持久化Spring Data JPA 6.1-6.2Spring Data JPA 用法介绍 6.3-6.4Spring Boot 集成,集成过程测试 6-5 -后台...
SpringBoot与Thymeleaf的整合是现代Java Web开发中常用的技术栈,它结合了Spring Boot的便捷性和Thymeleaf的动态模板引擎优势。这个名为"springboot-thymeleaf"的项目就是一个实例,展示了如何在Spring Boot应用中...
本项目实战框架结合了多个流行的开源技术,包括SpringBoot、Dubbo、MyBatis、Zookeeper以及Thymeleaf,旨在创建一个高效、可扩展且易于维护的Java应用。下面将详细解释这些技术及其在项目中的作用。 1. **...
`thymeleaf 学习笔记.pdf`可能是个人或社区整理的学习心得,涵盖了一些实战经验和常见问题的解决方法,对于初学者来说是非常有价值的参考资料。 10. **使用教程** `usingthymeleaf.pdf`和`thymeleaf 2.x.pdf`等...
IDEA环境下Spring Boot2 + Thymeleaf+ Mysql企业应用实战 图书进存销系统 具体显示:https://blog.csdn.net/sndayYU/article/details/92713320 如有问题请留言
基于SpringBoot+Mybatis+thymeleaf的学生信息管理系统 适合大学生作为 课程设计 javaWeb的课程设计 大作业 甚至,毕业设计,计算机毕业设计都可以。如果想用来作为自己学了SpringBoot和Mybatis的实战项目也是可以的...
五、实战应用 1. 数据展示:在表格、列表等元素中,利用`th:each`循环遍历后台传来的数据。 2. 表单验证:结合Spring Validation,利用Thymeleaf的`th:errors`显示错误信息。 3. 国际化:使用Thymeleaf的`th:i18n`...
《SpringBoot、Thymeleaf与Tiles整合实战详解》 在现代Web开发中,SpringBoot以其简洁、快速的特性受到了广大开发者的喜爱。而Thymeleaf和Tiles作为两个强大的视图层技术,能帮助我们构建更加优雅和可维护的前端...
### SpringBoot整合Shiro与Thymeleaf-权限管理实战 #### 一、Spring Boot简介 Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目标是简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式(默认...
基于springboot+mybatis+thymeleaf的学生信息管理系统源码+数据库.zip个人经导师指导并认可通过的98分课程设计项目,主要针对计算机相关专业的正在做课程设计、期末大作业的学生和需要项目实战练习的学习者。...