9)Thymeleaf ⼯具类对象表达式

x33g5p2x  于2021-12-24 转载在 其他  
字(16.7k)|赞(0)|评价(0)|浏览(380)

#execInfo

#execInfo:提供有关在 Thymeleaf 标准表达式内正在处理的模板的信息。

//See javadoc API for class org.thymeleaf.expression.ExecutionInfo

<body>
<p>#execInfo.templateName=[[${#execInfo.templateName}]]</p>
<p>#execInfo.templateMode=[[${#execInfo.templateMode}]]</p>
<p>#execInfo.processedTemplateName=[[${#execInfo.processedTemplateName}]]</p>
<p>#execInfo.processedTemplateMode=[[${#execInfo.processedTemplateMode}]]</p>
<p>#execInfo.templateNames=[[${#execInfo.templateNames}]]</p>
<p>#execInfo.templateModes=[[${#execInfo.templateModes}]]</p>
<p>#execInfo.templateStack=[[${#execInfo.templateStack}]]</p>
</body>

URIs/URLs

#uris:⽤于在 Thymeleaf 标准表达式中执⾏ URI / URL 操作(尤其是转义/取消转义)的⼯具对象。

// See javadoc API for class org.thymeleaf.expression.Uris
Escape/Unescape as a URI/URL path(对 URI、URL 转码)

${#uris.escapePath(uri)}   //转码
${#uris.escapePath(uri, encoding)}  //指定编码转码

${#uris.unescapePath(uri)}  //解码
${#uris.unescapePath(uri, encoding)}  //指定编码解码

<!--设置局部变量 url,用于操作转码-->
<body th:with="url='http://localhost/thymeleaf/user/home?u_id=9527&name=东方不败'">

<!--将转码结果存储为局部变量,方便输出和解码-->
<div th:with="escapePath=${#uris.escapePath(url)}">
    <p>被转码 url:[[${url}]]</p>
    <p>#uris.escapePath(uri) 转码后:[[${escapePath}]]</p>
    <p>#uris.unescapePath(uri) 解码后:[[${#uris.unescapePath(escapePath)}]]</p>
</div>
</body>

类似的还有:

${#uris.escapePathSegment(uri)}
${#uris.escapePathSegment(uri, encoding)}
${#uris.unescapePathSegment(uri)}
${#uris.unescapePathSegment(uri, encoding)}

${#uris.escapeFragmentId(uri)}
${#uris.escapeFragmentId(uri, encoding)}
${#uris.unescapeFragmentId(uri)}
${#uris.unescapeFragmentId(uri, encoding)}

${#uris.escapeQueryParam(uri)}
${#uris.escapeQueryParam(uri, encoding)}
${#uris.unescapeQueryParam(uri)}
${#uris.unescapeQueryParam(uri, encoding)}

Dates 日期工具类

#dates:java.util.Date 对象的实⽤程序⽅法。//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

(使用ISO8601格式格式化日期,也可以使用数组、列表或集合—————实际中这些用的少)

${#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')}

<body>
<!--/*后台输出:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse("1993-08-25 18:25:12");
model.addAttribute("birthday", date);
*/-->
<p th:text="'原日期:'+${birthday}"></p>
<p th:text="'yyyy-MM-dd HH:mm:ss:'+${#dates.format(birthday,'yyyy-MM-dd HH:mm:ss')}"></p>
<p th:text="'yyyy-MM-dd hh:mm:ss:'+${#dates.format(birthday,'yyyy-MM-dd hh:mm:ss')}"></p>
<p th:text="'yyyy-MM-dd HH:mm:'+${#dates.format(birthday,'yyyy-MM-dd HH:mm')}"></p>
<p th:text="'yyyy-MM-dd HH:'+${#dates.format(birthday,'yyyy-MM-dd HH')}"></p>
<p th:text="'yyyy-MM-dd:'+${#dates.format(birthday,'yyyy-MM-dd')}"></p>
<p th:text="'yyyy/MM/dd HH:mm:'+${#dates.format(birthday,'yyyy/MM/dd HH:mm')}"></p>
</body>

更多内容可参考官网:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#dates

Calendars 日期工具类

#calendars:类似于 #dates,但对于 java.util.Calendar 对象,See javadoc API for class org.thymeleaf.expression.Calendars

可参考官网:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#calendars

<body>
<!--/*后台输出:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse("1993-08-25 18:25:12");
model.addAttribute("birthday", date);
*/-->
<p th:text="'原日期:'+${birthday}"></p>
<p th:text="'yyyy-MM-dd HH:mm:ss:'+${#calendars.format(birthday,'yyyy-MM-dd HH:mm:ss')}"></p>
<p th:text="'yyyy-MM-dd hh:mm:ss:'+${#calendars.format(birthday,'yyyy-MM-dd hh:mm:ss')}"></p>
<p th:text="'yyyy-MM-dd HH:mm:'+${#calendars.format(birthday,'yyyy-MM-dd HH:mm')}"></p>
<p th:text="'yyyy-MM-dd HH:'+${#calendars.format(birthday,'yyyy-MM-dd HH')}"></p>
<p th:text="'yyyy-MM-dd:'+${#calendars.format(birthday,'yyyy-MM-dd')}"></p>
<p th:text="'yyyy/MM/dd HH:mm:'+${#calendars.format(birthday,'yyyy/MM/dd HH:mm')}"></p>
</body>

结果与 #datas 完全一样。

Numbers 数字工具类

#numbers:数字对象的实⽤程序⽅法,See javadoc API for class org.thymeleaf.expression.Numbers

用于格式化数字。
Set minimum integer digits. Also works with arrays, lists or sets

(设置最小整数位数。也适用于数组、列表或集合)

格式:${#numbers.formatInteger(num,size)}:num 表示被格式的数字,size 表示整数位最少保留几位。

<body>
<!--/*后台输出:model.addAttribute("age", 35);*/-->
<p th:text="'原数字:'+${age}"></p>
<p th:text="'0:'+${#numbers.formatInteger(age,0)}"></p>
<p th:text="'1:'+${#numbers.formatInteger(age,1)}"></p>
<p th:text="'2:'+${#numbers.formatInteger(age,2)}"></p>
<p th:text="'3:'+${#numbers.formatInteger(age,3)}"></p>
<p th:text="'4:'+${#numbers.formatInteger(age,4)}"></p>
</body>

Set minimum integer digits and thousands separator: 'POINT', 'COMMA', 'WHITESPACE', 'NONE' or 'DEFAULT' (bylocale). Also works with arrays, lists or sets

(设置最小整数位数和数以千计的分隔符:“点”、“逗号”、“空白”、“没有”或“默认”(字节环境)。也适用于数组、列表或集合)

格式:${#numbers.formatInteger(num,size,format)}:num 表示被格式的数字,size 表示整数位最少保留几位,format 表示格式,有: 'POINT', 'COMMA', 'WHITESPACE', 'NONE' or 'DEFAULT'

<body th:with="price=32008822">
<p th:text="'原数字:'+${price}"></p>
<p th:text="'POINT:'+${#numbers.formatInteger(price,0,'POINT')}"></p>
<p th:text="'COMMA:'+${#numbers.formatInteger(price,0,'COMMA')}"></p>
<p th:text="'WHITESPACE:'+${#numbers.formatInteger(price,0,'WHITESPACE')}"></p>
<p th:text="'NONE:'+${#numbers.formatInteger(price,0,'NONE')}"></p>
<p th:text="'DEFAULT:'+${#numbers.formatInteger(price,0,'DEFAULT')}"></p>
</body>

更多用法请参考官网:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#numbers

/*
 * ==========================
 * 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')}


/*
 * ==========================
 * 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 ⼯具类,就是字符串工具类,这以前 JSP 中的 JSTL 也有这种功能,如下所示,从方法名称即可猜到用途。

官网地址:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#strings

/*
 * ======================================================================
 * 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)}

官网地址:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#aggregates

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')}

相关文章