1. 程式人生 > >Spring Boot整合thymeleaf使用、thymeleaf常用標籤、thymeleaf常用語法

Spring Boot整合thymeleaf使用、thymeleaf常用標籤、thymeleaf常用語法

Spring Boot 推薦使用 Thymeleaf 來代替 JSP,Thymeleaf 模板到底是什麼來頭呢,下面我們來聊聊。

Thymeleaf 介紹

Thymeleaf 是一款用於渲染 XML/XHTML/HTML 5 內容的模板引擎。類似 JSP、Velocity、FreeMaker 等,它也可以輕易的與 Spring MVC 等 Web 框架進行整合作為 Web 應用的模板引擎。與其他模板引擎相比,Thymeleaf 最大的特點是能夠直接在瀏覽器中開啟並正確顯示模板頁面,而不需要啟動整個 Web 應用。

Thymeleaf 特點

簡單說,Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個極吸引人的特點:

Thymeleaf 在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。這是由於它支援 html 原型,然後在 html 標籤裡增加額外的屬性來達到模板+資料的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 Thymeleaf 的模板可以靜態地執行;當有資料返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
Thymeleaf 開箱即用的特性。它提供標準和 Spring 標準兩種方言,可以直接套用模板實現 JSTL、 OGNL 表示式效果,避免每天套模板、改 jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的方言。
Thymeleaf 提供 Spring 標準方言和一個與 SpringMVC 完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。
對比

好了,你們說了我們已經習慣使用了什麼 Velocity、FreMaker、Beetle 之類的模版,那麼到底好在哪裡呢?比一比吧!Thymeleaf 是與眾不同的,因為它使用了自然的模板技術。這意味著 Thymeleaf 的模板語法並不會破壞文件的結構,模板依舊是有效的 XML 文件。模板還可以用作工作原型,Thymeleaf 會在執行期替換掉靜態值。Velocity 與 FreeMarker 則是連續的文字處理器。

常用標籤語法介紹

1、常用語法

 

①、賦值、字串拼接

<p th:text="${userName}">neo</p>
<span th:text="'Welcome to our application, ' + ${userName} + '!'"></span>
<span th:text="|Welcome to our application, ${userName}!|"></span>

②、條件判斷 If/Unless

Thymeleaf 中使用 th:if 和 th:unless 屬性進行條件判斷,下面的例子中,<a>標籤只有在 th:if 中條件成立時才顯示

<a th:if="${flag == 'yes'}"  th:href="@{/home}"> home </a>
<a th:unless="${flag != 'no'}" th:href="@{http://www.ityouknow.com/}" >ityouknow</a>

th:unless 與 th:if 恰好相反,只有表示式中的條件不成立,才會顯示其內容。

也可以使用 (if) ? (then) : (else) 這種語法來判斷顯示的內容 

 

 

③、for 迴圈

<table>
    <tr  th:each="user,iterStat : ${users}">
        <td th:text="${user.name}">neo</td>
        <td th:text="${user.age}">6</td>
        <td th:text="${user.pass}">213</td>
        <td th:text="${iterStat.index}">index</td>
    </tr>
</table>

iterStat 稱作狀態變數,屬性有

  • index:當前迭代物件的 index(從 0 開始計算)
  • count:當前迭代物件的 index(從 1 開始計算)
  • size:被迭代物件的大小
  • current:當前迭代變數
  • even/odd:布林值,當前迴圈是否是偶數/奇數(從 0 開始計算)
  • first:布林值,當前迴圈是否是第一個
  • last:布林值,當前迴圈是否是最後一個

 

④、URL

URL 在 Web 應用模板中佔據著十分重要的地位,需要特別注意的是 Thymeleaf 對於 URL 的處理是通過語法 @{...} 來處理的。 如果需要 Thymeleaf 對 URL 進行渲染,那麼務必使用 th:href、th:src 等屬性,下面舉一個例子:

<a  th:href="@{http://www.ityouknow.com/{type}(type=${type})}">link1</a>

<a href="details.html" th:href="@{http://www.ityouknow.com/{pageId}/can-use-springcloud.html(pageId=${pageId})}">view</a>

 

 

設定背景:

<div th:style="'background:url(' + @{${img}} + ');'">

根據屬性值改變背景:

<div class="media-object resource-card-image"  th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>

 

幾點說明:

  • 上例中 URL 最後的 (pageId=${pageId}) 表示將括號內的內容作為 URL 引數處理,該語法避免使用字串拼接,大大提高了可讀性。
  • @{...} 表示式中可以通過 {pageId} 訪問 Context 中的 pageId 變數。
  • @{/order} 是 Context 相關的相對路徑,在渲染時會自動新增上當前 Web 應用的 Context 名字,假設 context 名字為 app,那麼結果應該是 /app/order。

⑤、內聯 [ [ ] ]

內聯文字:[[...]] 內聯文字的表示方式,使用時,必須先用在 th:inline="text/javascript/none" 啟用,th:inline 可以在父級標籤內使用,甚至作為 body 的標籤。內聯文字儘管比 th:text 的程式碼少,不利於原型顯示。

文字內聯:

<div th:inline="text" >
    <h1>內聯js</h1>
    <p>Hello, [[${userName}]]</p>
    <br/>
</div>

指令碼內聯,指令碼內聯可以在 js 中取到後臺傳過來的引數:

<script th:inline="javascript">
    var name = [[${userName}]] + ', Sebastian';
    alert(name);
</script>

 

 

 

⑥、內嵌變數

為了模板更加易用,Thymeleaf 還提供了一系列 Utility 物件(內置於 Context 中),可以通過 # 直接訪問:

  • dates:java.util.Date 的功能方法類
  • calendars: 類似 #dates,面向 java.util.Calendar
  • numbers:格式化數字的功能方法類
  • strings:字串物件的功能類,contains、startWiths、prepending/appending 等
  • objects:對 objects 的功能類操作
  • bools: 對布林值求值的功能方法
  • arrays:對陣列的功能類方法
  • lists:對 lists 的功能類方法
  • sets
  • maps

下面用一段程式碼來舉例一些常用的方法:

dates
<p th:text="${#dates.format(date, 'dd/MMM/yyyy HH:mm')}">neo</p>
<p th:text="${#dates.createToday()}">neo</p>
<p th:text="${#dates.createNow()}">neo</p>

strings
<p th:text="${#strings.isEmpty(userName)}">userName</p>
<p th:text="${#strings.listIsEmpty(users)}">userName</p>
<p th:text="${#strings.length(userName)}">userName</p>
<p th:text="${#strings.concat(userName)}"></p>

<p th:text="${#strings.randomAlphanumeric(count)}">userName</p>

 

2、常用th標籤

關鍵字

功能介紹

案例

th:id

替換id

<input th:id="'xxx' + ${collect.id}"/>

th:text 文字替換

<p th:text="${collect.description}">description</p>

th:utext

支html的文字替換 <p th:utext="${htmlcontent}">conten</p>
th:object 替換物件

<div th:object="${session.user}">

th:value 屬性賦值

<input th:value="${user.name}" />

th:with 變數賦值運算

<div th:with="isEven=${prodStat.count}%2==0"></div>

th:style 設定樣式

th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"

th:onclick 點選事件

th:onclick="'getCollect()'"

th:each 屬性賦值

tr th:each="user,userStat:${users}">

th:if 判斷條件

<a th:if="${userId == collect.userId}" >

th:unless 和th:if判斷相反

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

th:href 連結地址

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

th:switch 多路選擇 配合th:case 使用

<div th:switch="${user.role}">

th:case th:switch的一個分支

<p th:case="'admin'">User is an administrator</p>

th:fragment 佈局標籤,定義一個程式碼片段,方便其它地方引用

<div th:fragment="alert">

th:include 佈局標籤,替換內容到引入的檔案

<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />

th:replace 佈局標籤,替換整個標籤到引入的檔案

<div th:replace="fragments/header :: title"></div>

th:selected selected選擇框 選中

th:selected="(${xxx.id} == ${configObj.dd})"

th:src 圖片類地址引入

<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />

th:inline 定義js指令碼可以使用變數

<script type="text/javascript" th:inline="javascript">

th:action 表單提交的地址

<form action="subscribe.html" th:action="@{/subscribe}">

th:remove 刪除某個屬性

<tr th:remove="all">

1.all:刪除包含標籤和所有的子節點。2.body:不包含標記刪除,但刪除其所有的子節點。3.tag:包含標記的刪除,但不刪除它的子節點。4.all-but-first:刪除所有包含標籤的子節點,除了第一個。5.none:什麼也不做。這個值是有用的動態評估

th:attr 設定標籤屬性,多個屬性可以用逗號分隔 比如 th:attr="[email protected]{/image/aa.jpg},title=#{logo}",此標籤不太優雅,一般用的比較少

還有非常多的標籤,這裡只列出最常用的幾個,由於一個標籤內可以包含多個th:x屬性,其生效的優先順序順序為:

include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove。

推薦部落格:

Spring Boot2.0系列教程之模板引擎 Thymeleaf(四)