Configure
- 開發配置:
#開發階段選擇關閉緩存; spring.thymeleaf.cache=false spring.thymeleaf.mode=LEGACYHTML5
- 引入支持不嚴格檢測html的依賴:NoheHTML是一個html掃描器和標簽補全器;
<!-- 取消html嚴格驗證 --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> </dependency> <dependency> <groupId>org.unbescape</groupId> <artifactId>unbescape</artifactId> <version>1.1.6.RELEASE</version> </dependency>
- 引入命名空間:
<html xmlns:th="http://www.thymeleaf.org">
語法規則
- th:text,改變當前元素里面的文本內容
- 表達式
${} 變量表達式,獲取對象屬性、調用方法、使用內置的基本對象(ctx、request、response、session)、內置的工具對象
*{} 變量選擇表達式,跟 ${} 一樣,配合 th:object 使用
@{} URL表達式,定義 url 鏈接
~{} 片段引用表達式
#{} 獲取國際化內容 - 標准變量表達式:${msg},msg兩段可以有空格,大小寫敏感;
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
- 選擇變量表達式:*{msg},配合標准變量表達式簡化屬性獲取;
<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>
- URL表達式:@{msg},取動態變量用;
<!-- 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>
3.Attributes
- action
<form action="subscribe.html" th:action="@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form>
- each:Note that the
prod
iter variable is scoped to the<tr>
element, which means it is available to inner tags like<td>
.<table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> <th>COMMENTS</th> </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:unless="${#lists.isEmpty(prod.comments)}">view</a> </td> </tr> </table>
屬性 th:each 包含一些狀態變量:
- index:當前迭代器下標,0 開始;
- count:當前迭代器下標,1 開始;
- size:迭代器變量的元素總數;
- current:迭代器的每一個迭代變量;
- even/odd:判斷是否當前迭代為奇數、偶數次;
- first:判斷當前是否是第一次迭代;
- last:判斷當前是否是最后一次迭代;
- href & if:產品帶有品論信息時顯示;
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
- unless
<span th:unless="${gender == '0'}"> 男 </span> <span th:unless="${gender == '1'}"> 女 </span>
- switch/case
<div th:switch="${gender}"> <p th:case="1">male</p> <p th:case="0">female</p> </div>
- object
- text
- value
- attr