9)Thymeleaf ⼯具類物件表示式
目錄
#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')}