1. 程式人生 > >thymeleaf 基本語法

thymeleaf 基本語法

四、標準表示式語法

· 簡單表示式 (simple expressions)

  ${...}  變量表達式

  *{...}  選擇變量表達式

  #{...}  訊息表示式

  @{...}  連結url表示式

· 字面量

  'one text','another one!',...   文字

  0,34,3.0,12.3,... 數值

  true false 布林型別

  null 空

one,sometext,main 文字字元

· 文字操作

  +  字串連線

  |The name is ${name}|  字串連線

· 算術運算

  + , - , * , / , %  二元運算子

  -  負號(一元運算子)

· 布林操作

  and,or  二元操作符

  !,not 非(一元操作符)

· 關係操作符

  > , < , >= , <= (gt , lt , ge , le)

  == , != (eq, ne)

· 條件判斷

(if) ? (then)      if-then

(if) ? (then) : (else)   if-then-else  

<tr th:class="${row.even}? 'even' : 'odd'">
  ...
</tr>

條件表示式中的三個部分自身也可以是表示式,也可以是變數(${...}, *{...}), 訊息(#{...}), URL (@{...}) 或字面量 ('...')
條件表示式也可以使用括號來巢狀:

<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
...
</tr>

else表示式也可以省略,當條件為false時,會返回null:

<tr th:class="${row.even}? 'alt'">
...
</tr>

(value) ?: (defaultvalue)   Default

只有在第一個表示式返回null時,第二個表示式才會運算

·表示式工具物件

  • #dates 與java.util.Date物件的方法對應,格式化、日期元件抽取等等
  • #calendars 類似#dates,與java.util.Calendar物件對應
  • #numbers 格式化數字物件的工具方法
  • #strings 與java.lang.String對應的工具方法:contains、startsWith、prepending/appending等等
  • #objects 用於物件的工具方法
  • #bools 用於布林運算的工具方法
  • #arrays 用於陣列的工具方法
  • #lists 用於列表的工具方法
  • #sets 用於set的工具方法
  • #maps 用於map的工具方法
  • #aggregates 用於建立陣列或集合的聚合的工具方法
  • #messages 用於在變量表達式內部獲取外化訊息的工具方法,與#{…}語法獲取的方式相同
  • #ids 用於處理可能重複出現(例如,作為遍歷的結果)的id屬性的工具方法

·連結URL
URL在web模板中是一級重要元素,使用@{…}表示

URL的型別:

  絕對URL:

  • http://www.thymeleaf.org

  相對URL:

  • 頁面相對: user/login.html
  • 上下文相對:/itemdetails?id=3 (伺服器上下文名稱會被自動新增)
  • 伺服器相對:~/billing/processInvoice(允許呼叫同一伺服器上的另一個上下文中的URL)
  • 協議相對://code.jquery.com/jquery-2.0.3.min.js

Thymeleaf在任何情況下都可以處理絕對URL,對於相對URL,則需要使用一個實現了IWebContext介面的上下文物件,這個物件包含了來自HTTP請求的資訊,這些資訊用於建立相對連結。

<!-- 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提供預處理表達式的功能。

它是在錶殼式正常執行前執行的操作,允許修改最終將要被執行的表示式。

預處理表達式跟正常的一樣,但被兩個下劃線包圍住,例如:__${expression}__

假設有一個i18n訊息檔案Message_fr.properties,裡面有一個條目包含了一個呼叫具體語言的靜態方法的OGNL表示式:

[email protected]@translateToFrench({0})

Messages_es.properties中的等價條目:

[email protected]@translateToSpanish({0})

可以根據locale先建立用於運算表示式的標記片段,本例中,先通過預處理選擇表示式,然後讓Thymeleaf處理這個選擇出來的表示式:

<p th:text="${__#{article.text('textVar')}__}">Some text here...</p>

對於locale為French的情況,上面的表示式經過預處理後,得出的等價物如下:

<p th:text="${@[email protected](textVar)}">Some text here...</p>

五、 設定屬性值
th:attr 任何屬性值

<form action="subscribe.html" th:attr="[email protected]{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>

多個屬性一起設定,用逗號隔開

<img src="../../images/gtvglogo.png" th:attr="[email protected]{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

設定指定屬性

th:abbr th:accept th:accept-charset
th:accesskey th:action th:align
th:alt th:archive th:audio
th:autocomplete th:axis th:background
th:bgcolor th:border th:cellpadding
th:cellspacing th:challenge th:charset
th:cite th:class th:classid ...
<input type="submit" value="Subscribe me!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">
<li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

設定多個屬性在同一時間  有兩個特殊的屬性可以這樣設定: th:alt-title 和 th:lang-xmllang

th:alt-title 設定 alt 和 title 
th:lang-xmllang 設定 lang 和 xml:lang 

<img src="../../images/gtvglogo.png" th:attr="[email protected]{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

<img src="../../images/gtvglogo.png"th:src="@{/images/gtvglogo.png}" th:title="#{logo}" th:alt="#{logo}" />

<img src="../../images/gtvglogo.png"th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" />

前置和後置新增屬性值  th:attrappend 和 th:attrprepend

<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />

編譯後:

<input type="button" value="Do it!" class="btn warning" />

還有兩個特定的新增屬性 th:classappendth:styleappend

<tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">

修復的布林屬性

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

所有修復的布林屬性:

|th:async |th:autofocus |th:autoplay |

|th:checked |th:controls |th:declare |

|th:default |th:defer |th:disabled |

|th:formnovalidate|th:hidden |th:ismap |

|th:loop |th:multiple |th:novalidate |

|th:nowrap |th:open |th:pubdate |

|th:readonly |th:required |th:reversed |

|th:scoped |th:seamless |th:selected |

HTML5友好的屬性及元素名

<table>
    <tr data-th-each="user : ${users}">
        <td data-th-text="${user.login}">...</td>
        <td data-th-text="${user.name}">...</td>
    </tr>
</table>

data-{prefix}-{name}是編寫HTML5自定義屬性的標準語法,不需要開發者使用th:*這樣的名稱空間,Thymeleaf讓這種語法自動對所有dialect都可用。

六、遍歷

·基礎

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

可遍歷的物件:實現java.util.Iterable、java.util.Map(遍歷時取java.util.Map.Entry)、array、任何物件都被當作只有物件自身一個元素的列表

·狀態

  • 當前遍歷索引,從0開始,index屬性
  • 當前遍歷索引,從1開始,count屬性
  • 總元素數量,size屬性
  • 每一次遍歷的iter變數,current屬性
  • 當前遍歷是even還是odd,even/odd布林屬性
  • 當前遍歷是第一個,first布林屬性
  • 當前遍歷是最後一個,last布林屬性
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  <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>

若不指定狀態變數,Thymeleaf會預設生成一個名為“變數名Stat”的狀態變數:

<tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
  <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>

七、條件運算

<tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  <td>
    <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
    <a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
  </td>
</tr>
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>

th:if 不只運算布林條件,它對以下情況也運算為true:

·值不為null
  值為boolean且為true
  值為數字且非0
  值為字元且非0
  值是字串且不是:“false”,“off”,“no”
  值不是boolean、數字、字元、字串
·如果值為null,則th:if運算結果為false

th:if的反面是th:unless

<a href="comments.html" th:href="@{/comments(prodId=${prod.id})}"  th:unless="${#lists.isEmpty(prod.comments)}">view</a>

th:switch 和 th:case

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

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