Thymeleaf实战

理解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提供了满足大多数情况下的默认实现-标准方言(后面会介绍自定义方言):

  1. 引入标签库(命名空间),常用的一种方式:
    Java代码  
    1. <span th:text="">....</span>  
     需要引入命名空间
    Html代码  
    1. <html xmlns:th="http://www.thymeleaf.org">  
  2. HTML5标准,自定义属性:
    Html代码  
    1. <span data-th-text="">.....</span>  
    Html代码  
    1. <table>  
    2.     <tr data-th-each="user : ${users}">  
    3.         <td data-th-text="${user.login}">...</td>  
    4.         <td data-th-text="${user.name}">...</td>  
    5.     </tr>  
    6. </table>  
     这样可以省去命名空间

Thymeleaf基本语法

标准表达式

  • 变量表达式

语法:${...}

用法:

Html代码  
  1. <th:text="${book.author}"></p>  
  • 消息表达式

语法:#{...}

用法:

Html代码  
  1. <th:text="#{home.welcome}">Welcome to our grocery store!</p>  

相当于消息的一个key,也称文本外部化,一般用于国际化等外部配置文件,其中properties文件内容为

Java代码  
  1. home.welcome=welcome to thymeleaf  

目前消息文件中的内容是固定的,如果我们需要向消息中动态插入一个参数以便实现动态消息,可以#{messageKey(param=value)},多个参数用,分割-#{messageKey(param1=value1, param2=value2)},messageKey本身也可以是一个变量表达式:

Java代码  
  1. home.welcome=welcome to {0}  
Java代码  
  1. <p th:utext="#{home.welcome(${session.user.name})}">   
  2.        Welcome to our grocery store, Sebastian Pepper!   
  3. </p>  
  4.   
  5. <p th:utext="#{${welcomeMsgKey}(${session.user.name})}">  
  6.   Welcome to our grocery store, Sebastian Pepper!  
  7. </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进行修改

  • 选择表达式

语法:*{...}

示例:

Html代码  
  1. <div th:object="${session.book}">  
  2. <p>Name: <span th:text="*{title}">thymeleaf实战</span>.</p>  
  3. <p>Surname: <span th:text="*{author}">Peppa</span>.</p>  
  4. <p>Nationality: <span th:text="*{price}">300</span>.</p>  
  5. </div>  

与变量表达式的区别:它们是在当前选择的对象而不是整个上下文变量映射上执行(性能高)

  • 链接表达式

语法:@{...}

示例

绝对url: 

Html代码  
  1. <th:href="@{http://www.thymeleaf.org}" th:text="">...</>  

相对url,可以是:

  1. 相对url: user/login.html
  2. 上下文相对: /itemdetails?id=3 (自动添加服务器中的应用上下文名称)
  3. 服务器相对: ~/billing/processInvoice (允许在同一服务器的另一个上下文(=应用程序)中调用URL).
  4. 协议相对: //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>
  • 片段表达式

     片段表达式是表示标记片段并围绕模板移动它们的简单方法。这允许我们复制它们,将它们作为参数传递给其他模板,等等

语法:~{...}

示例:

Java代码  
  1. <div th:align="center" th:fragment="footer">  
  2. ....  
  3. </div>  
 定义片段
Html代码  
  1. <div th:insert="~{commons :: footer}">...</div>  
 使用th:insert or th:replace插入片段,它们可以在任何地方使用,就像任何其他变量一样:
Html代码  
  1. <div th:with="frag=~{footer :: #footer/text()}">  
  2. <th:insert="${frag}">  
  3. </div>  

Thymeleaf基本语法

字面量

  • 文本字面量: 'one text''Another one!',…
<p th:text="'<h1>我是一个香蕉,蕉蕉蕉蕉蕉蕉</h1>'"</p>  

<p th:utext="'<h1>我是一个香蕉,蕉蕉蕉蕉蕉蕉</h1>'"</p>  

区别:th:text对html标签转义,th:utext不转义,解析为html内容  
  • 数字字面量: 0343.012.3,…
  • Boolean 字面量: truefalse
  • Null 值字面量: null
  • 文字标记: onesometextmain,…(不需要单引号'',这些令牌允许在标准表达式中进行一点简化。它们的工作与文本文字('...')完全相同,但它们只允许使用字母(A-Za-z),数字(0-9),括号([]),点(.),连字符(-)和下划线(_)。所以没有空白,没有逗号等)
  • 文本操作:
    • 字符串连接: +
    • 文字替换: |The name is ${name}|
  • 算术运算符:
    • 二元运算符: +-*/%
    • 减号(一元运算): -
  • 逻辑运算符:
    • 二元运算符: andor
    • 逻辑非(一元运算符): !not
  • 比较运算符:
    • 比较运算符: ><>=<= (gtltgele)
    • 相等比较: ==!= (eqne)
  • 条件运算符:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • Special tokens:
    • No-Operation(无操作): _          如果条件不满足,保留在原型中定义的值(文本)
<p th:utext="${user.username}?:_">我是原型的值</p>

设置属性值

  • Java模版引擎:Thymeleaf是一个用于Web和独立环境的现代服务器端Java模板引擎。能够处理

设置任意属性值-->th:attr

Html代码  
  1. <form action="subscribe.html" th:attr="action=@{/subscribe}">  
  2.   <fieldset>  
  3.     <input type="text" name="email" />  
  4.     <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>  
  5.   </fieldset>  
  6. </form>  

设置值到指定的属性---->HTML5标签的常用属性。如:

Html代码  
  1. <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>  
  2. <form action="subscribe.html" th:action="@{/subscribe}">  
  3. <li><href="product/list.html" th:href="@{/product/list}">Product List</a></li>  

固定值布尔属性---->属性就代表值

Html代码  
  1. <input type="checkbox" name="active" th:checked="${user.active}" />  

迭代器

基本的迭代---->th:each

Html代码  
  1. <li th:each="book:${books}" th:text="${book.title}"></li>  

   ${books}为迭代变量(作用域中的Iterable,Enumeration,Iterator,Map,Entry,Array及字符串等,相当于标准标签库中<c:forEach>里的items属性);

  book为当前迭代的元素,相当于var属性

  状态变量:跟踪迭代器的状态(相当于标准标签库的varStatus标签)

Java代码  
  1. <table>  
  2.   <tr>  
  3.     <th>NAME</th>  
  4.     <th>PRICE</th>  
  5.     <th>IN STOCK</th>  
  6.   </tr>  
  7.   <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">  
  8.     <td th:text="${prod.name}">Onions</td>  
  9.     <td th:text="${prod.price}">2.41</td>  
  10.     <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>  
  11.   </tr>  
  12. </table>  

index:当前迭代索引,从0开始。

count:当前迭代索引,从1开始。

size:迭代变量中元素的总数。

current:每个迭代的ITER变量。

even/odd:当前迭代是偶数还是奇数。

first:当前迭代是否为第一个元素。

last:当前迭代是否为最后一个元素。

条件语句

th:if

Html代码  
  1. <href="comments.html"  
  2. th:href="@{/product/comments(prodId=${prod.id})}"   
  3. th:if="${not #lists.isEmpty(prod.comments)}">view</a>  

th:unless---->条件不成立

Html代码  
  1. <href="comments.html"  
  2. th:href="@{/comments(prodId=${prod.id})}"   
  3. th:unless="${#lists.isEmpty(prod.comments)}">view</a>  
      th:switch/th:case
Html代码  
  1. <div th:switch="${user.role}">  
  2.   <th:case="'admin'">User is an administrator</p>  
  3.   <th:case="#{roles.manager}">User is a manager</p>  
  4.   <th:case="*">User is some other thing</p>  
  5. </div>  

模板布局

在我们的模板中,我们通常希望包括来自其他模板的部件,如页脚、页眉、菜单等部件(公共部分);或是固定的模板格式渲染成不同的内容,如邮件模板,商品详情页模板…
为了做到这一点,thymeleaf需要我们定义这些部分,“片段”,以便包含,这可以使用th:fragment属性完成。
假设我们想在所有杂货店页面中添加一个标准的版权页脚,那么我们创建一个/templates/footer.html文件,其中包含以下代码:

Java代码  
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3.   <body>  
  4.     <div th:fragment="copy">  
  5.       &copy; 2011 The Good Thymes Virtual Grocery  
  6.     </div>  
  7.   </body>  
  8. </html>  

 使用th:insert或者th:replace插入片段,th:include只插入片段内容(不推荐使用)

Java代码  
  1. <body>  
  2.   ...  
  3.   <div th:insert="~{footer :: copy}"></div>  
  4. </body>  

 其中footer为模板名称,copy为片段名称,也可以不使用th:fragment,使用格式如下

Java代码  
  1. <div id="copy-section">  
  2.   &copy; 2011 The Good Thymes Virtual Grocery  
  3. </div>  
  4. ...  
  5. <body>  
  6.   ...  
  7.   <div th:insert="~{footer :: #copy-section}"></div>  
  8. </body>  

注释

标准html/xml注释

thymeleaf解析器级注释

Java代码  
  1. <!--/* 
  2.   <div th:text="${...}"> 
  3.     ... 
  4.   </div> 
  5. */-->  
      原型注释块[静态时注释,模板执行时显示
Html代码  
  1. <!--/*/  
  2.   <div th:text="${...}">  
  3.     ...  
  4.   </div>  
  5. /*/-->  

内联

直接将表达式写在文本中而非标签中,js,css中使用常见

Js代码  
  1. <script th:inline="javascript">  
  2.     ...  
  3. var username = [[${session.user.name}]];  
  4.     ...  
  5. </script>  

格式:[[...]]或者[(...)]分别对应th:text和th:utext

禁用内联---->th:inline="none"

表达式基本对象(隐式对象,存在于上下文中)

#ctx:上下文对象
Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.context.IContext 
  4.  * ====================================================================== 
  5.  */  
  6. ${#ctx.locale}  
  7. ${#ctx.variableNames}  
  8.   
  9. /* 
  10.  * ====================================================================== 
  11.  * See javadoc API for class org.thymeleaf.context.IWebContext 
  12.  * ====================================================================== 
  13.  */  
  14.   
  15. ${#ctx.request}  
  16. ${#ctx.response}  
  17. ${#ctx.session}  
  18. ${#ctx.servletContext}  
#locale:直接访问与java.util.Locale关联的当前请求
Java代码  
  1. ${#locale}  
 param:获取请求相关的属性,如请求参数,request.getParmeter("")等
Java代码  
  1. /* 
  2.  * ============================================================================ 
  3.  * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap 
  4.  * ============================================================================ 
  5.  */  
  6.   
  7. ${param.foo}  //request.getParameterValues("foo")              
  8. ${param.size()}  
  9. ${param.isEmpty()}  
  10. ${param.containsKey('foo')}  
  11. ...  
session: for retrieving session attributes.
Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. ${session.foo}  // session.getAtttribute('foo')  
  8. ${session.size()}  
  9. ${session.isEmpty()}  
  10. ${session.containsKey('foo')}  
  11. ...  

application : for retrieving application/servlet context attributes.

Java代码  
  1. /* 
  2.  * ============================================================================= 
  3.  * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap 
  4.  * ============================================================================= 
  5.  */  
  6.   
  7. ${application.foo}      //servletContext.getAtttribute('foo')  
  8. ${application.size()}  
  9. ${application.isEmpty()}  
  10. ${application.containsKey('foo')}  
  11. ${myRequestAttribute}
  12. ...

Web 上下文对象

#request : 当前请求javax.servlet.http.HttpServletRequest .

Java代码  
  1. ${#request.getAttribute('foo')}  
  2. ${#request.getParameter('foo')}  
  3. ${#request.getContextPath()}  
  4. ${#request.getRequestName()}  
  5. ...  

#session : javax.servlet.http.HttpSession

Java代码  
  1. ${#session.getAttribute('foo')}  
  2. ${#session.id}  
  3. ${#session.lastAccessedTime}  
  4. ...  

#servletContext : javax.servlet.ServletContext

Java代码  
  1. ${#servletContext.getAttribute('foo')}  
  2. ${#servletContext.contextPath}  
  3. ...  

标准方言中包含的thymeleaf的唯一元素处理器(不是属性)是th:block。
th:block是一个属性容器,允许模板开发人员指定他们想要的属性。thymeleaf将执行这些属性,然后简单地使块(而不是其内容)消失。
因此,它可能很有用,例如,当创建迭代表时,每个元素需要一个以上的<tr>,或者需要条件判断时

Html代码  
  1. <table>  
  2.   <th:block th:each="user : ${users}">  
  3.     <tr>  
  4.         <td th:text="${user.login}">...</td>  
  5.         <td th:text="${user.name}">...</td>  
  6.     </tr>  
  7.     <tr>  
  8.         <td colspan="2" th:text="${user.address}">...</td>  
  9.     </tr>  
  10.   </th:block>  
  11. </table>  

实用对象

      这些使用表达式对象在package org.thymeleaf.expression包下都有对应的类,如果不知道怎么使用直接看Javadoc就好,推荐使用的时候按需查询。

Messages

#messages : 用于在变量表达式中获得外部消息的实用方法,与使用#{…}语法获得的方式相同.

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Messages 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. ${#messages.msg('msgKey')}  
  8. ${#messages.msg('msgKey', param1)}  
  9. ${#messages.msg('msgKey', param1, param2)}  
  10. ${#messages.msg('msgKey', param1, param2, param3)}  
  11. ${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})}  
  12. ${#messages.arrayMsg(messageKeyArray)}  
  13. ${#messages.listMsg(messageKeyList)}  
  14. ${#messages.setMsg(messageKeySet)}  
  15.   
  16. ${#messages.msgOrNull('msgKey')}  
  17. ${#messages.msgOrNull('msgKey', param1)}  
  18. ${#messages.msgOrNull('msgKey', param1, param2)}  
  19. ${#messages.msgOrNull('msgKey', param1, param2, param3)}  
  20. ${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})}  
  21. ${#messages.arrayMsgOrNull(messageKeyArray)}  
  22. ${#messages.listMsgOrNull(messageKeyList)}  
  23. ${#messages.setMsgOrNull(messageKeySet)}  

URIs/URLs

#uris : 用于在Thymeleaf标准表达式中执行URI / URL操作(特别是转义/消除转义)的实用对象.

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Uris 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Escape/Unescape as a URI/URL path 
  9.  */  
  10. ${#uris.escapePath(uri)}  
  11. ${#uris.escapePath(uri, encoding)}  
  12. ${#uris.unescapePath(uri)}  
  13. ${#uris.unescapePath(uri, encoding)}  
  14.   
  15. /* 
  16.  * Escape/Unescape as a URI/URL path segment (between '/' symbols) 
  17.  */  
  18. ${#uris.escapePathSegment(uri)}  
  19. ${#uris.escapePathSegment(uri, encoding)}  
  20. ${#uris.unescapePathSegment(uri)}  
  21. ${#uris.unescapePathSegment(uri, encoding)}  
  22.   
  23. /* 
  24.  * Escape/Unescape as a Fragment Identifier (#frag) 
  25.  */  
  26. ${#uris.escapeFragmentId(uri)}  
  27. ${#uris.escapeFragmentId(uri, encoding)}  
  28. ${#uris.unescapeFragmentId(uri)}  
  29. ${#uris.unescapeFragmentId(uri, encoding)}  
  30.   
  31. /* 
  32.  * Escape/Unescape as a Query Parameter (?var=value) 
  33.  */  
  34. ${#uris.escapeQueryParam(uri)}  
  35. ${#uris.escapeQueryParam(uri, encoding)}  
  36. ${#uris.unescapeQueryParam(uri)}  
  37. ${#uris.unescapeQueryParam(uri, encoding)}   

Conversions

#conversions : 允许在模板的任意位置执行转换服务的实用程序对象:

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Conversions 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Execute the desired conversion of the 'object' value into the 
  9.  * specified class. 
  10.  */  
  11. ${#conversions.convert(object, 'java.util.TimeZone')}  
  12. ${#conversions.convert(object, targetClass)}  

Dates

#dates : 为 java.util.Date对象提供工具方法,比如:格式化,提取年月日等:

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Dates 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. ${#dates.format(date)}  
  8. ${#dates.arrayFormat(datesArray)}  
  9. ${#dates.listFormat(datesList)}  
  10. ${#dates.setFormat(datesSet)}  
  11.   
  12. ${#dates.formatISO(date)}  
  13. ${#dates.arrayFormatISO(datesArray)}  
  14. ${#dates.listFormatISO(datesList)}  
  15. ${#dates.setFormatISO(datesSet)}  
  16.   
  17.   
  18. ${#dates.format(date, 'dd/MMM/yyyy HH:mm')}  
  19. ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}  
  20. ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}  
  21. ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}  
  22.   
  23. ${#dates.day(date)}                    // also arrayDay(...), listDay(...), etc.  
  24. ${#dates.month(date)}                  // also arrayMonth(...), listMonth(...), etc.  
  25. ${#dates.monthName(date)}              // also arrayMonthName(...), listMonthName(...), etc.  
  26. ${#dates.monthNameShort(date)}         // also arrayMonthNameShort(...), listMonthNameShort(...), etc.  
  27. ${#dates.year(date)}                   // also arrayYear(...), listYear(...), etc.  
  28. ${#dates.dayOfWeek(date)}              // also arrayDayOfWeek(...), listDayOfWeek(...), etc.  
  29. ${#dates.dayOfWeekName(date)}          // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.  
  30. ${#dates.dayOfWeekNameShort(date)}     // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.  
  31. ${#dates.hour(date)}                   // also arrayHour(...), listHour(...), etc.  
  32. ${#dates.minute(date)}                 // also arrayMinute(...), listMinute(...), etc.  
  33. ${#dates.second(date)}                 // also arraySecond(...), listSecond(...), etc.  
  34. ${#dates.millisecond(date)}            // also arrayMillisecond(...), listMillisecond(...), etc.  
  35.   
  36. /* 
  37.  * Create date (java.util.Date) objects from its components 
  38.  */  
  39. ${#dates.create(year,month,day)}  
  40. ${#dates.create(year,month,day,hour,minute)}  
  41. ${#dates.create(year,month,day,hour,minute,second)}  
  42. ${#dates.create(year,month,day,hour,minute,second,millisecond)}  
  43.   
  44. /* 
  45.  * Create a date (java.util.Date) object for the current date and time 
  46.  */  
  47. ${#dates.createNow()}  
  48.   
  49. ${#dates.createNowForTimeZone()}  
  50.   
  51. /* 
  52.  * Create a date (java.util.Date) object for the current date (time set to 00:00) 
  53.  */  
  54. ${#dates.createToday()}  
  55.   
  56. ${#dates.createTodayForTimeZone()}  

Calendars

#calendars : 类似于#dates , 但是只针对java.util.Calendar对象:

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Calendars 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Format calendar with the standard locale format 
  9.  * Also works with arrays, lists or sets 
  10.  */  
  11. ${#calendars.format(cal)}  
  12. ${#calendars.arrayFormat(calArray)}  
  13. ${#calendars.listFormat(calList)}  
  14. ${#calendars.setFormat(calSet)}  
  15.   
  16. /* 
  17.  * Format calendar with the ISO8601 format 
  18.  * Also works with arrays, lists or sets 
  19.  */  
  20. ${#calendars.formatISO(cal)}  
  21. ${#calendars.arrayFormatISO(calArray)}  
  22. ${#calendars.listFormatISO(calList)}  
  23. ${#calendars.setFormatISO(calSet)}  
  24.   
  25. /* 
  26.  * Format calendar with the specified pattern 
  27.  * Also works with arrays, lists or sets 
  28.  */  
  29. ${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')}  
  30. ${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')}  
  31. ${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')}  
  32. ${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')}  
  33.   
  34. /* 
  35.  * Obtain calendar properties 
  36.  * Also works with arrays, lists or sets 
  37.  */  
  38. ${#calendars.day(date)}                // also arrayDay(...), listDay(...), etc.  
  39. ${#calendars.month(date)}              // also arrayMonth(...), listMonth(...), etc.  
  40. ${#calendars.monthName(date)}          // also arrayMonthName(...), listMonthName(...), etc.  
  41. ${#calendars.monthNameShort(date)}     // also arrayMonthNameShort(...), listMonthNameShort(...), etc.  
  42. ${#calendars.year(date)}               // also arrayYear(...), listYear(...), etc.  
  43. ${#calendars.dayOfWeek(date)}          // also arrayDayOfWeek(...), listDayOfWeek(...), etc.  
  44. ${#calendars.dayOfWeekName(date)}      // also arrayDayOfWeekName(...), listDayOfWeekName(...), etc.  
  45. ${#calendars.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(...), listDayOfWeekNameShort(...), etc.  
  46. ${#calendars.hour(date)}               // also arrayHour(...), listHour(...), etc.  
  47. ${#calendars.minute(date)}             // also arrayMinute(...), listMinute(...), etc.  
  48. ${#calendars.second(date)}             // also arraySecond(...), listSecond(...), etc.  
  49. ${#calendars.millisecond(date)}        // also arrayMillisecond(...), listMillisecond(...), etc.  
  50.   
  51. /* 
  52.  * Create calendar (java.util.Calendar) objects from its components 
  53.  */  
  54. ${#calendars.create(year,month,day)}  
  55. ${#calendars.create(year,month,day,hour,minute)}  
  56. ${#calendars.create(year,month,day,hour,minute,second)}  
  57. ${#calendars.create(year,month,day,hour,minute,second,millisecond)}  
  58.   
  59. ${#calendars.createForTimeZone(year,month,day,timeZone)}  
  60. ${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)}  
  61. ${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)}  
  62. ${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)}  
  63.   
  64. /* 
  65.  * Create a calendar (java.util.Calendar) object for the current date and time 
  66.  */  
  67. ${#calendars.createNow()}  
  68.   
  69. ${#calendars.createNowForTimeZone()}  
  70.   
  71. /* 
  72.  * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00) 
  73.  */  
  74. ${#calendars.createToday()}  
  75.   
  76. ${#calendars.createTodayForTimeZone()}  

Numbers

#numbers : 为数值型对象提供工具方法:

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Numbers 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * ========================== 
  9.  * Formatting integer numbers 
  10.  * ========================== 
  11.  */  
  12.   
  13. /*  
  14.  * Set minimum integer digits. 
  15.  * Also works with arrays, lists or sets 
  16.  */  
  17. ${#numbers.formatInteger(num,3)}  
  18. ${#numbers.arrayFormatInteger(numArray,3)}  
  19. ${#numbers.listFormatInteger(numList,3)}  
  20. ${#numbers.setFormatInteger(numSet,3)}  
  21.   
  22.   
  23. /*  
  24.  * Set minimum integer digits and thousands separator:  
  25.  * 'POINT', 'COMMA', 'WHITESPACE', 'NONE' or 'DEFAULT' (by locale). 
  26.  * Also works with arrays, lists or sets 
  27.  */  
  28. ${#numbers.formatInteger(num,3,'POINT')}  
  29. ${#numbers.arrayFormatInteger(numArray,3,'POINT')}  
  30. ${#numbers.listFormatInteger(numList,3,'POINT')}  
  31. ${#numbers.setFormatInteger(numSet,3,'POINT')}  
  32.   
  33.   
  34. /* 
  35.  * ========================== 
  36.  * Formatting decimal numbers 
  37.  * ========================== 
  38.  */  
  39.   
  40. /* 
  41.  * Set minimum integer digits and (exact) decimal digits. 
  42.  * Also works with arrays, lists or sets 
  43.  */  
  44. ${#numbers.formatDecimal(num,3,2)}  
  45. ${#numbers.arrayFormatDecimal(numArray,3,2)}  
  46. ${#numbers.listFormatDecimal(numList,3,2)}  
  47. ${#numbers.setFormatDecimal(numSet,3,2)}  
  48.   
  49. /* 
  50.  * Set minimum integer digits and (exact) decimal digits, and also decimal separator. 
  51.  * Also works with arrays, lists or sets 
  52.  */  
  53. ${#numbers.formatDecimal(num,3,2,'COMMA')}  
  54. ${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}  
  55. ${#numbers.listFormatDecimal(numList,3,2,'COMMA')}  
  56. ${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}  
  57.   
  58. /* 
  59.  * Set minimum integer digits and (exact) decimal digits, and also thousands and  
  60.  * decimal separator. 
  61.  * Also works with arrays, lists or sets 
  62.  */  
  63. ${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}  
  64. ${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')}  
  65. ${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')}  
  66. ${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')}  
  67.   
  68.   
  69. /*  
  70.  * ===================== 
  71.  * Formatting currencies 
  72.  * ===================== 
  73.  */  
  74.   
  75. ${#numbers.formatCurrency(num)}  
  76. ${#numbers.arrayFormatCurrency(numArray)}  
  77. ${#numbers.listFormatCurrency(numList)}  
  78. ${#numbers.setFormatCurrency(numSet)}  
  79.   
  80. /*  
  81.  * ====================== 
  82.  * Formatting percentages 
  83.  * ====================== 
  84.  */  
  85.   
  86. ${#numbers.formatPercent(num)}  
  87. ${#numbers.arrayFormatPercent(numArray)}  
  88. ${#numbers.listFormatPercent(numList)}  
  89. ${#numbers.setFormatPercent(numSet)}  
  90.   
  91. /*  
  92.  * Set minimum integer digits and (exact) decimal digits. 
  93.  */  
  94. ${#numbers.formatPercent(num, 3, 2)}  
  95. ${#numbers.arrayFormatPercent(numArray, 3, 2)}  
  96. ${#numbers.listFormatPercent(numList, 3, 2)}  
  97. ${#numbers.setFormatPercent(numSet, 3, 2)}  
  98.   
  99. /* 
  100.  * =============== 
  101.  * Utility methods 
  102.  * =============== 
  103.  */  
  104. /* 
  105.  * Create a sequence (array) of integer numbers going 
  106.  * from x to y 
  107.  */  
  108. ${#numbers.sequence(from,to)}  
  109. ${#numbers.sequence(from,to,step)}  

Strings

#strings : 为String 对象提供工具方法。如: contains, startsWith, prepending/appending等:

Objects

#objects : 为object 对象提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Objects 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Return obj if it is not null, and default otherwise 
  9.  * Also works with arrays, lists or sets 
  10.  */  
  11. ${#objects.nullSafe(obj,default)}  
  12. ${#objects.arrayNullSafe(objArray,default)}  
  13. ${#objects.listNullSafe(objList,default)}  
  14. ${#objects.setNullSafe(objSet,default)}   

Booleans

#bools : 为boolean 对象提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Bools 
  4.  * ====================================================================== 
  5.  */  

Arrays

#arrays : 为arrays 对象提供常用的工具方法;

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Arrays 
  4.  * ====================================================================== 
  5.  */  
  6. /* 
  7.  * Converts to array, trying to infer array component class. 
  8.  * Note that if resulting array is empty, or if the elements 
  9.  * of the target object are not all of the same class, 
  10.  * this method will return Object[]. 
  11.  */  
  12. ${#arrays.toArray(object)}  
  13.   
  14. /* 
  15.  * Convert to arrays of the specified component class. 
  16.  */  
  17. ${#arrays.toStringArray(object)}  
  18. ${#arrays.toIntegerArray(object)}  
  19. ${#arrays.toLongArray(object)}  
  20. ${#arrays.toDoubleArray(object)}  
  21. ${#arrays.toFloatArray(object)}  
  22. ${#arrays.toBooleanArray(object)}  
  23. /* 
  24.  * Compute length 
  25.  */  
  26. ${#arrays.length(array)}  
  27.   
  28. /* 
  29.  * Check whether array is empty 
  30.  */  
  31. ${#arrays.isEmpty(array)}  
  32.   
  33. /* 
  34.  * Check if element or elements are contained in array 
  35.  */  
  36. ${#arrays.contains(array, element)}  
  37. ${#arrays.containsAll(array, elements)}  

Lists

#lists :为lists对象提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Lists 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Converts to list 
  9.  */  
  10. ${#lists.toList(object)}  
  11.   
  12. /* 
  13.  * Compute size 
  14.  */  
  15. ${#lists.size(list)}  
  16.   
  17. /* 
  18.  * Check whether list is empty 
  19.  */  
  20. ${#lists.isEmpty(list)}  
  21.   
  22. /* 
  23.  * Check if element or elements are contained in list 
  24.  */  
  25. ${#lists.contains(list, element)}  
  26. ${#lists.containsAll(list, elements)}  
  27.   
  28. /* 
  29.  * Sort a copy of the given list. The members of the list must implement 
  30.  * comparable or you must define a comparator. 
  31.  */  
  32. ${#lists.sort(list)}  
  33. ${#lists.sort(list, comparator)}  

Sets

#sets : 为lists对象提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Sets 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Converts to set 
  9.  */  
  10. ${#sets.toSet(object)}  
  11.   
  12. /* 
  13.  * Compute size 
  14.  */  
  15. ${#sets.size(set)}  
  16.   
  17. /* 
  18.  * Check whether set is empty 
  19.  */  
  20. ${#sets.isEmpty(set)}  
  21.   
  22. /* 
  23.  * Check if element or elements are contained in set 
  24.  */  
  25. ${#sets.contains(set, element)}  
  26. ${#sets.containsAll(set, elements)}  

Maps

#maps : 为lists对象提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Maps 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Compute size 
  9.  */  
  10. ${#maps.size(map)}  
  11.   
  12. /* 
  13.  * Check whether map is empty 
  14.  */  
  15. ${#maps.isEmpty(map)}  
  16.   
  17. /* 
  18.  * Check if key/s or value/s are contained in maps 
  19.  */  
  20. ${#maps.containsKey(map, key)}  
  21. ${#maps.containsAllKeys(map, keys)}  
  22. ${#maps.containsValue(map, value)}  
  23. ${#maps.containsAllValues(map, value)}  

Aggregates

#aggregates : 为创造一个arrays 或者 collections聚集函数提供常用的工具方法

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Aggregates 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Compute sum. Returns null if array or collection is empty 
  9.  */  
  10. ${#aggregates.sum(array)}  
  11. ${#aggregates.sum(collection)}  
  12.   
  13. /* 
  14.  * Compute average. Returns null if array or collection is empty 
  15.  */  
  16. ${#aggregates.avg(array)}  
  17. ${#aggregates.avg(collection)}  

IDs

#ids :为可能需要循环的ID属性提供常用的工具方法.

Java代码  
  1. /* 
  2.  * ====================================================================== 
  3.  * See javadoc API for class org.thymeleaf.expression.Ids 
  4.  * ====================================================================== 
  5.  */  
  6.   
  7. /* 
  8.  * Normally used in th:id attributes, for appending a counter to the id attribute value 
  9.  * so that it remains unique even when involved in an iteration process. 
  10.  */  
  11. ${#ids.seq('someId')}  
  12.   
  13. /* 
  14.  * Normally used in th:for attributes in <label> tags, so that these labels can refer to Ids 
  15.  * generated by means if the #ids.seq(...) function. 
  16.  * 
  17.  * Depending on whether the <label> goes before or after the element with the #ids.seq(...) 
  18.  * function, the "next" (label goes before "seq") or the "prev" function (label goes after  
  19.  * "seq") function should be called. 
  20.  */  
  21. ${#ids.next('someId')}  
  22. ${#ids.prev('someId')}  
  • 下一章节介绍在spring mvc中使用以及在springboot中使用
posted @ 2022-06-15 17:31  Tiger-Adan  阅读(174)  评论(0编辑  收藏  举报