1. 程式人生 > >SpringBoot-thymeleaf模板語法簡介

SpringBoot-thymeleaf模板語法簡介

本想簡單說一下thymeleaf模板語法,因為畢竟後邊SpringSecurity用到的語法很少,結果總結起來有點兒多…

先說句有用的廢話:
thymeleaf模板語法,都以th屬性開頭,如:

<span th:text="...">

一,thymeleaf-簡單表示式

1.變量表達式
2.選擇或星號表示式
3.文字國際化表示式
4.URL表示式

1,變量表達式

Thymeleaf模板引擎在進行模板渲染時,還會附帶一個Context存放進行模板渲染的變數,在模板中定義的表示式本質上就是從Context中獲取對應的變數的值

<p>Today is: <span
th:text="${day}">
2 November 2016</span>.</p>
假設day的值為2016年11月2日,那麼渲染結果為:<p>Today is: 2016年11月2日.</p>。
注意 : 渲染後,模板中span值2 November 2016將被覆蓋

2,選擇(星號)表示式

可以簡單理解為內層是對外層物件的引用

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span
>
.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div>

等同於以下方式:

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span
>
.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p> </div>

也可以混用,如下:

<div th:object="${session.user}">
  <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
如何沒有與th:object結合使用,*{}與${}效果一樣,因為其範圍自動擴充套件到context。

3,URL表示式

URL表示式指的是把一個有用的上下文或會話資訊新增到URL,這個過程經常被叫做URL重寫。
Thymeleaf對於URL的處理是通過語法@{…}來處理的

<!— 絕對路徑 —>
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

<!— 相對路徑 帶引數—>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
Thymeleaf支援相對路徑和絕對路徑
(orderId=${o.id})表示將括號內的內容作為URL引數處理
@{...}表示式中可以通過{orderId}訪問Context中的orderId變數
@{/order}是Context相關的相對路徑,在渲染時會自動新增上當前Web應用的Context名字,假設context名字為app,那麼結果應該是/app/order

4,文字國際化表示式

文字國際化表示式允許我們從一個外部檔案獲取區域文字資訊(.properties)
使用Key-Value方式,還可以提供一組引數(可選).

.properties

#{main.title}
#{message.entrycreated(${entryId})}

模板引用:

<table>
    <th th:text="#{header.address.city}">...</th>
    <th th:text="#{header.address.country}">...</th>
</table>

二.thymeleaf-字面值

  1.文字文字:’one text’, ‘Another one!’,…
  2.文字數量:0, 34, 3.0, 12.3,…
  3.布林型常量:true, false
  4.空的文字:null
  5.文字標記:one, sometext, main,…
  

三:thymeleaf-文字處理

1.字串拼接:+

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

2.文字替換:|The name is ${name}|

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

相比以上兩種方式都可以實現字串合併,但是,|…|中只能包含變量表達式${…},不能包含其他常量、條件表示式等。

四.表達基本物件

  1.#ctx:上下文物件

  2.#vars:上下文變數

  3.#locale:上下文語言環境

  4.#httpServletRequest:(只有在Web上下文)HttpServletRequest物件

  5.#httpSession:(只有在Web上下文)HttpSession物件。

例如:

<span th:text="${#locale.country}">US</span>.

th:text="${#calendars.format(today,'dd MMMM yyyy')}"

五,表示式預處理

表示式預處理,它被定義在_之間:

#{selection.__${sel.code}__}
${sel.code}將先被執行,結果(假如是AAA)將被看做表示式的一部分被執行
結果#{為selection.AAA}。

六,thymeleaf運算子

在表示式中可以使用各類算術運算子,例如+, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

邏輯運算子>, <, <=,>=,==,!=都可以使用
需要注意的是使用 > ,<, >=, <=時需要用它的HTML轉義符(> gt; < lt; >= ge; gte; <= le; lte; == eq; != ne; neq;)

th:if="${prodStat.count} &gt; 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

布林運算子 and,or

七,thymeleaf迴圈

資料集合必須是可以遍歷的,使用th:each標籤:

<body>
  <h1>Product list</h1>

  <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>

  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>
被迴圈渲染的元素<tr>中加入th:each標籤
th:each="prod : ${prods}"對集合變數prods進行遍歷,物件prod在迴圈體中可通過表示式訪問

八,thymeleaf條件求值

1,If/Unless

Thymeleaf中使用th:if和th:unless屬性進行條件判斷

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

th:unless與th:if相反,表示式條件不成立時顯示內容。

2,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>

3.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>

4.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>

九,Thymeleaf-Utilities

Thymeleaf提供了套Utility物件,內置於Context中,可通過#直接訪問:

- #dates: java.util的實用方法。物件:日期格式、元件提取等.
- #calendars: 類似於#日期,但對於java.util。日曆物件
- #numbers: 格式化數字物件的實用方法。
- #strings:字串物件的實用方法:包含startsWith,將/附加等。
- #objects: 實用方法的物件。
- #bools: 布林評價的實用方法。
- #arrays: 陣列的實用方法。
- #lists: list集合。
- #sets:set集合。
- #maps: map集合。
- #aggregates: 實用程式方法用於建立聚集在陣列或集合.
- #messages: 實用程式方法獲取外部資訊內部變量表達式,以同樣的方式,因為他們將獲得使用# {…}語法
- #ids: 實用程式方法來處理可能重複的id屬性(例如,由於迭代)。

Dates

#dates : utility methods for java.util.Date objects:
/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Dates
 * ======================================================================
 */

/*
 * Null-safe toString()
 */
${#strings.toString(obj)}                           // also array*, list* and set*

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

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

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

/*
 * Create a calendar (java.util.Calendar) object for the current date and time
 */
${#calendars.createNow()}

/*
 * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00)
 */
${#calendars.createToday()}

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

/*
 * 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(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

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

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

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

相關推薦

SpringBoot-thymeleaf模板語法簡介

本想簡單說一下thymeleaf模板語法,因為畢竟後邊SpringSecurity用到的語法很少,結果總結起來有點兒多… 先說句有用的廢話: thymeleaf模板語法,都以th屬性開頭,如: <span th:text="...">

SpringBoot---Thymeleaf 模板引擎

一、使用Thymeleaf模板引擎開發     1.在pom.xml檔案中引入Thymeleaf依賴    <!--引入Thymeleaf 模板引擎--> <dependency

springBoot預設模板引擎Thymeleaf簡介

由於springBoot預設的是jar包形式,所以不支援,jsp。因此我們需要模板引擎。 JSP、Velocity、Freemarker、Thymeleaf模板引擎的大致原理:頁面+資料交給模板引擎(寫一個頁面模板,裡面一些值是動態的,我們用表示式形式,表達。例如下圖中的t

springbootthymeleaf模板的paginate分頁

display source for charset lan 引擎 封裝 protected hiberna 本文根據一個簡單的user表為例,展示 springboot集成mybatis,再到前端分頁完整代碼(新手自學,不足之處歡迎糾正); 先看java部分 pom.xm

springboot mail+Thymeleaf模板

from ann () ria sage code pool color final compile ‘org.springframework.boot:spring-boot-starter-thymeleaf‘ compile ‘io.ratpack:rat

springbootthymeleaf模板問題springbootthymeleaf模板問題

fix pid source pen html5標簽 需要 嚴格 thymeleaf cef springboot項目引入thymeleaf模板時,默認thymeleaf模板對html5標簽是嚴格檢查的。要實現非嚴格檢查 1. 在項目中加NekoHTML庫 在Maven中添

SpringBoot集成Thymeleaf模板引擎

lis arr type www mode html中 object erro pub 傳統的JSP+JSTL組合是已經過去了,Thymeleaf是Java服務端的模板引擎,與傳統的JSP不同,Thymeleaf可以使用瀏覽器直接打開,因為可以忽略掉拓展屬性,相當於打開原生

springboot-thymeleaf動態模板生成

thymeleaf 會有 tee pom cache string gte emp context thymeleaf動態模板: Map data = new HashMap(); data.put("code", "1234"); SpringTemplateEngin

SpringBootThymeleaf模板

視圖解析 web 應用 text true fix content return uuid ddr 閱讀目錄 一、前言二、集成 Thymeleaf 模板引擎三、使用 Thymeleaf 模板回到頂部一、前言Thymeleaf 的出現是為了取代 JSP,雖然 JSP 存在了很

springboot:Java模板引擎Thymeleaf介紹

mvc 選擇 ssi dash 其他 art pattern 開發環境 表示 Thymeleaf是一款用於渲染XML/XHTML/HTML5內容的模板引擎。類似JSP,Velocity,FreeMaker等,它也可以輕易的與Spring MVC等Web框架進行集成作為W

thymeleaf 模板介紹+表示式語法

         thymeleaf和jsp一樣是模板引擎,模板頁面裡面可以解析html xml js css等,thymeleaf獨有的優勢,它完全遵照html5的規則來寫的 ,看起來和html5頁面一樣,既可以給標籤設定預設值,也可以使用表示式給

3.SpringBoot整合Thymeleaf模板

一、前言 SrpingBoot支援如JSP、Thymeleaf、FreeMarker、Mustache、Velocity等各種模板引擎,同時還為開發者提供了自定義模板擴充套件的支援。 使用嵌入式Servlet容器時,請避免使用JSP,因為使用JSP打包後會存在一些限制。 在SpringBoot使用上述模

SpringBoot學習之路】11.Thymeleaf模板引擎

轉載宣告:商業轉載請聯絡作者獲得授權,非商業轉載請註明出處.原文來自 © 呆萌鍾【SpringBoot學習之路】11.Thymeleaf模板引擎  模板引擎簡介 JSP、Velocity、Freemarker、Thymeleaf SpringB

SpringBoot第二篇:web(基於Thymeleaf模板

接著第一篇,繼續配置web專案。 1、在pom檔案中加入: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-sta

瞭解微服務以及Springboot整合mybaits+thymeleaf模板引擎實戰D經驗分享

前言: 首先肯定大家最想知道的還是Spring boot到底是幹啥的?其實我也是初學者,雖然接觸時間不長,但是也想把自己的理解和大家做一個交流。 簡單來說,Springboot就是一個更加靈活,配置起來更簡單,廣泛應用於微服務的一個開源框架。那大家肯定還會問,到

springboot 使用 thymeleaf 模板引擎。在頁面寫隱藏域接收後臺的值。在頁面進行對話方塊提示。

場景: 當頁面 有個活動資訊的開啟按鈕,點選開啟按鈕,到後臺進行驗證,這個活動是否過期或者重複。如果有,頁面進行對話方塊提示。 1、後臺邏輯判斷 if else。當開啟狀態是 進入if。進行判斷,負責執行修改狀態。 2、通過 model 進行賦值傳到前臺的隱藏域 if(status

SpringBoot HTML頁面使用thymeleaf模板開發(3)

1,新建一個專案pom檔案映入相關jar包了。一定要引入thymeleaf。 pox檔案主要是引入web和thymeleaf。 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven

SpringBoot匯入thymeleaf模板,執行報錯。

報錯: SpringBoot匯入thymeleaf模板,執行報錯org.xml.sax.SAXParseException: 元素型別 “link” 必須由匹配的結束標記 終止。 1、新建SpringBoot MAVEN專案後 JAR型別的專案 2、新增pom.xml檔案

springboot專案中使用thymeleaf模板引擎引入js庫失效

js資原始檔所處位置: 在html檔案引用js庫 <script src="../static/scripts/jquery-1.7.2.min..js">

SpringBootThymeleaf模板.

一、前言     Thymeleaf 的出現是為了取代 JSP,雖然 JSP 存在了很長時間,並在 Java Web 開發中無處不在,但是它也存在一些缺陷: 1、JSP 最明顯的問題在於它看起來像HTML或XML,但它其實上並不是。大多數的JSP模板都是採用HTML的形式,但是又摻雜上了各種JSP標籤庫的