模板引擎-Thymeleaf 簡單筆記
1、thymeleaf簡介
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
現代化、服務端Java模板引擎
2、基本語法
1、表示式
表示式名字 |
語法 |
用途 |
變數取值 |
${...} |
獲取請求域、session域、物件等值 |
選擇變數 |
*{...} |
獲取上下文物件值 |
訊息 |
#{...} |
獲取國際化等值 |
連結 |
@{...} |
生成連結 |
片段表示式 |
~{...} |
jsp:include 作用,引入公共頁面片段 |
2、字面量
文字值: 'one text' , 'Another one!' ,…數字: 0 , 34 , 3.0 , 12.3 ,…布林值: true , false
空值: null
變數: one,two,.... 變數不能有空格
3、文字操作
字串拼接: +
變數替換: |The name is ${name}|
4、數學運算
運算子: + , - , * , / , %
5、布林運算
運算子: and
一元運算: ! , not
6、比較運算
比較: > , < , >= , <= ( gt , lt , ge , le )等式: == , != ( eq , ne )
7、條件運算
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
8、特殊操作
無操作: _
3、設定屬性值-th:attr
設定單個值
<form action="subscribe.html" th:attr="action=@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form>
設定多個值
<img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
以上兩個的代替寫法 th:xxxx
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/> <form action="subscribe.html" th:action="@{/subscribe}">
所有h5相容的標籤寫法
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes
4、迭代
<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>
<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>
5、條件運算
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<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>
6、屬性優先順序
轉載:https://www.yuque.com/atguigu/springboot/vgzmgh