Spring Boot 采用Thymeleaf模块及Thymeleaf语法
2017-8-1
| 2023-6-7
0  |  0 分钟
type
status
date
slug
summary
tags
category
icon
password
标签

Thymeleaf简介

Thymeleaf是⾯向Web和独⽴环境的现代服务器端Java模板引擎,能够处 理HTML,XML,JavaScript,CSS甚⾄纯⽂本。
Thymeleaf旨在提供⼀个优雅的、⾼度可维护的创建模板的⽅式。 为了实 现这⼀⽬标,Thymeleaf建⽴在⾃然模板的概念上,将其逻辑注⼊到模板 ⽂件中,不会影响模板设计原型。 这改善了设计的沟通,弥合了设计和 开发团队之间的差距。
Thymeleaf从设计之初就遵循Web标准——特别是HTML5标准 ,如果需 要,Thymeleaf允许您创建完全符合HTML5验证标准的模板。

在Spring Boot中使用

引入依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

配置文件

#thymeleaf start spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html #开发时关闭缓存,不然没法看到实时页面 spring.thymeleaf.cache=false #thymeleaf end
resources/templates为thymeleaf模板默认路径

编写Controller

@Controller public class TestController { @RequestMapping("/test") public String test(ModelMap map) { map.addAttribute("title", "Hello Thymeleaf!"); return "test"; } }

编写test.html模块

<!DOCTYPE html> <html xmlns="<http://www.w3.org/1999/xhtml>" xmlns:th="<http://www.thymeleaf.org>"> <head> <title>测试</title> </head> <body> <h1 th:text="${title}">标题</h1> </body> </html>

使用LEGACYHTML5模板

默认配置下,thymeleaf对.html的内容要求很严格,比如 <input name="id"/>,如果少最后的标签封闭符号/,就会报错而转到错误页。也比如你在使用Vue.js这样的库,然后有<div v-cloak></div>这样的html代码,也会被thymeleaf认为不符合要求而抛出错误。
解决这个问题可以通过设置thymeleaf模板为 LEGACYHTML5可以解决这个问题.LEGACYHTML5需要搭配一个额外的库 NekoHTML才可用。

引入依赖

<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>

修改配置文件

#thymeleaf start #采用LEGCYHTML5模板 spring.thymeleaf.mode=LEGACYHTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html #开发时关闭缓存,不然没法看到实时页面 spring.thymeleaf.cache=false #thymeleaf end

Thymeleaf语法

Thymeleaf简单表达式

变量表达式

Thymeleaf模板引擎在进行模板渲染时,还会附带一个Context存放进行模板渲染的变量,在模板中定义的表达式本质上就是从Context中获取对应的变量的值
<h1 th:text="${title}">标题</h1>

选择(星号)表达式

可以简单理解为内层对外层对象的引用
<div th:object="${user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> </div>
以上代码等同于:
<div> <p>Name: <span th:text="${user.firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${user.lastName}">Pepper</span>.</p> </div>
如何没有与 th:object结合使用,*{}${}效果一样,因为其范围自动扩展到context。

URL表达式

URL表达式指的是把一个有用的上下文或会话信息添加到URL,这个过程经常被叫做URL重写。Thymeleaf对于URL的处理是通过语法@{…}来处理的
<!— 绝对路径 —> <a href="details.html" th:href="@{<http://127.0.0.1/detail(id=${id})>}">view</a> <!— 相对路径 带参数—> <a href="details.html" th:href="@{/order/details(id=${id})}">view</a> <!-- 把参数拼进路径中 --> <a href="details.html" th:href="@{/order/{id}/details(id=${id})}">view</a>
Thymeleaf支持相对路径和绝对路径 (id=${id})表示将括号内的内容作为URL参数处理 @{...}表达式中可以通过{id}访问Context中的id变量 @{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order

文字国际化表达式

文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties) 使用Key-Value方式,还可以提供一组参数(可选).
#{main.title} #{message.entrycreated(${entryId})}
模板引用:
<table> <th th:text="#{header.address.city}">...</th> <th th:text="#{header.address.country}">...</th> </table>

Thymeleaf文本处理

字符串拼接

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

文字替换

<span th:text="|Welcome to our application, ${user.name}!|">
相比以上两种方式都可以实现字符串合并,但是,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。

Thymeleaf表达基本对象

  • #ctx:上下文对象
  • #vars:上下文变量
  • #locale:上下文语言环境
  • #httpServletRequest:(只有在Web上下文)HttpServletRequest对象
  • #httpSession:(只有在Web上下文)HttpSession对象。
例如:
<span th:text="${#locale.country}">US</span>. <div th:text="${#calendars.format(today,'dd MMMM yyyy')}"></div>

表达式预处理

表达式预处理,它被定义在_之间:
#{selection.__${sel.code}__}
${sel.code}将先被执行,结果(假如是AAA)将被看做表达式的一部分被执行,结果为 #{selection.AAA}

Thymeleaf运算符

在表达式中可以使用各类算术运算符,例如+, -, *, /, %
<div th:with="isEven=(${prodStat.count} % 2 == 0)"></div>
逻辑运算符>, <, <=,>=,==,!=都可以使用 需要注意的是使用 > ,<, >=, <=时需要用它的HTML转义符(> gt; < lt; >= ge; gte; <= le; lte; == eq; != ne; neq;)
<div th:if="${prodStat.count} > 1"></div> <div th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"></div>
布尔运算符 and,or

Thymeleaf循环

数据集合必须是可以遍历的,使用 th:each标签:
<table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> </tr> <tr th:each="prod : ${prods}"> <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>
被循环渲染的元素<tr>中加入 th:each标签 th:each="prod : ${prods}"对集合变量prods进行遍历,对象prod在循环体中可通过表达式访问

Thymeleaf条件求值

If/Unless

Thymeleaf中使用 th:ifth:unless属性进行条件判断
设置标签只有在 th:if中条件成立时才显示:
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:unlessth:if相反,表达式条件不成立时显示内容。

Switch

多路选择 Switch结构,默认属性 default,用 *表示
<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>

If-then-else

(if)?(then):else 三元运算符
三元运算控制 class属性选择
<tr th:class="${row.even}? 'even' : 'odd'">
三元运算嵌套
<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
还可以省略 else部分,当表达式结果为 false,返回 null,否则返回 alt
<tr th:class="${row.even}? 'alt'"></tr>

If-then

(if) ? (then) ,省略了 else部分,如果条件不成立,返回 null
如果第一个表达式的计算结果为null,则取第二个表达式的结果
<div th:object="${session.user}"> <p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p> </div>
等效于:
<p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>
条件表达式嵌套:
<p>Name: <span th:text="*{firstName} ?: (*{admin} ? 'Admin' : #{default.username})">Sebastian</span>.</p>

Expression Utility Objects

Thymeleaf提供了套Utility对象,内置于Context中,可通过#直接访问:
  • #execInfo : expression object providing useful information about the template being processed inside Thymeleaf Standard Expressions.
  • #uris : utility object for performing URI/URL operations (esp. escaping/unescaping) inside Thymeleaf Standard Expressions.
  • #conversions : utility object that allows the execution of the Conversion Service at any point of a template
  • #dates: java.util的实用方法。对象:日期格式、组件提取等.
  • #calendars: 类似于#日期,但对于 java.util。日历对象
  • #numbers: 格式化数字对象的实用方法。
  • #strings:字符串对象的实用方法:包含 startsWith,将/附加等。
  • #objects: 实用方法的对象。
  • #bools: 布尔评价的实用方法。
  • #arrays: 数组的实用方法。
  • #lists: list集合。
  • #sets:set集合。
  • #maps: map集合。
  • #aggregates: 实用程序方法用于创建聚集在数组或集合.
  • #messages: 实用程序方法获取外部信息内部变量表达式,以同样的方式,因为他们将获得使用# {…}语法
  • #ids: 实用程序方法来处理可能重复的id属性(例如,由于迭代)。

Execution Info

  • #execInfo : expression object providing useful information about the template being processed inside Thymeleaf Standard Expressions.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.ExecutionInfo * ====================================================================== */ /* * Return the name and mode of the 'leaf' template. This means the template * from where the events being processed were parsed. So if this piece of * code is not in the root template "A" but on a fragment being inserted * into "A" from another template called "B", this will return "B" as a * name, and B's mode as template mode. */ ${#execInfo.templateName} ${#execInfo.templateMode} /* * Return the name and mode of the 'root' template. This means the template * that the template engine was originally asked to process. So if this * piece of code is not in the root template "A" but on a fragment being * inserted into "A" from another template called "B", this will still * return "A" and A's template mode. */ ${#execInfo.processedTemplateName} ${#execInfo.processedTemplateMode} /* * Return the stacks (actually, List<String> or List<TemplateMode>) of * templates being processed. The first element will be the * 'processedTemplate' (the root one), the last one will be the 'leaf' * template, and in the middle all the fragments inserted in nested * manner to reach the leaf from the root will appear. */ ${#execInfo.templateNames} ${#execInfo.templateModes} /* * Return the stack of templates being processed similarly (and in the * same order) to 'templateNames' and 'templateModes', but returning * a List<TemplateData> with the full template metadata. */ ${#execInfo.templateStack}

Messages

  • #messages : utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Messages * ====================================================================== */ /* * Obtain externalized messages. Can receive a single key, a key plus arguments, * or an array/list/set of keys (in which case it will return an array/list/set of * externalized messages). * If a message is not found, a default message (like '??msgKey??') is returned. */ ${#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)} /* * Obtain externalized messages or null. Null is returned instead of a default * message if a message for the specified key is not found. */ ${#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 : utility object for performing URI/URL operations (esp. escaping/unescaping) inside Thymeleaf Standard Expressions.
/* * ====================================================================== * 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 : utility object that allows the execution of the Conversion Service at any point of a template:
/* * ====================================================================== * 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 : utility methods for java.util.Date objects: /* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Dates * ====================================================================== */ /* * Format date with the standard locale format * Also works with arrays, lists or sets */ ${#dates.format(date)} ${#dates.arrayFormat(datesArray)} ${#dates.listFormat(datesList)} ${#dates.setFormat(datesSet)} /* * Format date with the ISO8601 format * Also works with arrays, lists or sets */ ${#dates.formatISO(date)} ${#dates.arrayFormatISO(datesArray)} ${#dates.listFormatISO(datesList)} ${#dates.setFormatISO(datesSet)} /* * Format date with the specified pattern * Also works with arrays, lists or sets */ ${#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')} /* * Obtain date properties * Also works with arrays, lists or sets */ ${#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 : analogous to #dates, but for java.util.Calendar objects:
/* * ====================================================================== * 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 : utility methods for number objects:
/* * ====================================================================== * 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 : utility methods for String objects:
/* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Strings * ====================================================================== */ /* * Null-safe toString() */ ${#strings.toString(obj)} // also array*, list* and set* /* * Check whether a String is empty (or null). Performs a trim() operation before check * Also works with arrays, lists or sets */ ${#strings.isEmpty(name)} ${#strings.arrayIsEmpty(nameArr)} ${#strings.listIsEmpty(nameList)} ${#strings.setIsEmpty(nameSet)} /* * Perform an 'isEmpty()' check on a string and return it if false, defaulting to * another specified string if true. * Also works with arrays, lists or sets */ ${#strings.defaultString(text,default)} ${#strings.arrayDefaultString(textArr,default)} ${#strings.listDefaultString(textList,default)} ${#strings.setDefaultString(textSet,default)} /* * Check whether a fragment is contained in a String * Also works with arrays, lists or sets */ ${#strings.contains(name,'ez')} // also array*, list* and set* ${#strings.containsIgnoreCase(name,'ez')} // also array*, list* and set* /* * Check whether a String starts or ends with a fragment * Also works with arrays, lists or sets */ ${#strings.startsWith(name,'Don')} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set* /* * Substring-related operations * Also works with arrays, lists or sets */ ${#strings.indexOf(name,frag)} // also array*, list* and set* ${#strings.substring(name,3,5)} // also array*, list* and set* ${#strings.substringAfter(name,prefix)} // also array*, list* and set* ${#strings.substringBefore(name,suffix)} // also array*, list* and set* ${#strings.replace(name,'las','ler')} // also array*, list* and set* /* * Append and prepend * Also works with arrays, lists or sets */ ${#strings.prepend(str,prefix)} // also array*, list* and set* ${#strings.append(str,suffix)} // also array*, list* and set* /* * Change case * Also works with arrays, lists or sets */ ${#strings.toUpperCase(name)} // also array*, list* and set* ${#strings.toLowerCase(name)} // also array*, list* and set* /* * Split and join */ ${#strings.arrayJoin(namesArray,',')} ${#strings.listJoin(namesList,',')} ${#strings.setJoin(namesSet,',')} ${#strings.arraySplit(namesStr,',')} // returns String[] ${#strings.listSplit(namesStr,',')} // returns List<String> ${#strings.setSplit(namesStr,',')} // returns Set<String> /* * Trim * Also works with arrays, lists or sets */ ${#strings.trim(str)} // also array*, list* and set* /* * Compute length * Also works with arrays, lists or sets */ ${#strings.length(str)} // also array*, list* and set* /* * Abbreviate text making it have a maximum size of n. If text is bigger, it * will be clipped and finished in "..." * Also works with arrays, lists or sets */ ${#strings.abbreviate(str,10)} // also array*, list* and set* /* * Convert the first character to upper-case (and vice-versa) */ ${#strings.capitalize(str)} // also array*, list* and set* ${#strings.unCapitalize(str)} // also array*, list* and set* /* * Convert the first character of every word to upper-case */ ${#strings.capitalizeWords(str)} // also array*, list* and set* ${#strings.capitalizeWords(str,delimiters)} // also array*, list* and set* /* * Escape the string */ ${#strings.escapeXml(str)} // also array*, list* and set* ${#strings.escapeJava(str)} // also array*, list* and set* ${#strings.escapeJavaScript(str)} // also array*, list* and set* ${#strings.unescapeJava(str)} // also array*, list* and set* ${#strings.unescapeJavaScript(str)} // also array*, list* and set* /* * Null-safe comparison and concatenation */ ${#strings.equals(first, second)} ${#strings.equalsIgnoreCase(first, second)} ${#strings.concat(values...)} ${#strings.concatReplaceNulls(nullValue, values...)} /* * Random */ ${#strings.randomAlphanumeric(count)}

Objects

  • #objects : utility methods for objects in general
/* * ====================================================================== * 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 : utility methods for boolean evaluation /* * ====================================================================== * See javadoc API for class org.thymeleaf.expression.Bools * ====================================================================== */ /* * Evaluate a condition in the same way that it would be evaluated in a th:if tag * (see conditional evaluation chapter afterwards). * Also works with arrays, lists or sets */ ${#bools.isTrue(obj)} ${#bools.arrayIsTrue(objArray)} ${#bools.listIsTrue(objList)} ${#bools.setIsTrue(objSet)} /* * Evaluate with negation * Also works with arrays, lists or sets */ ${#bools.isFalse(cond)} ${#bools.arrayIsFalse(condArray)} ${#bools.listIsFalse(condList)} ${#bools.setIsFalse(condSet)} /* * Evaluate and apply AND operator * Receive an array, a list or a set as parameter */ ${#bools.arrayAnd(condArray)} ${#bools.listAnd(condList)} ${#bools.setAnd(condSet)} /* * Evaluate and apply OR operator * Receive an array, a list or a set as parameter */ ${#bools.arrayOr(condArray)} ${#bools.listOr(condList)} ${#bools.setOr(condSet)}

Arrays

  • #arrays : utility methods for 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 : utility methods for 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 : utility methods for sets
/* * ====================================================================== * 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 : utility methods for maps
/* * ====================================================================== * 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 : utility methods for creating aggregates on arrays or 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 : utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
/* * ====================================================================== * 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')}
参考资料:Thymeleaf文档
SpringBoot
  • SpringBoot
  • Thymeleaf
  • Spring Boot搭建Restful API输出Json数据异常Spring Boot 采用自定义注解方式实现AOP日志记录
    目录