Spring Boot(四):Thymeleaf 使用詳解

​在上篇文章Spring Boot (二):Web 綜合開發中簡單介紹了一下 Thymeleaf,這篇文章將更加全面詳細的介紹 Thymeleaf 的使用。Thymeleaf 是新一代的模板引擎,在 Spring4.0 中推薦使用 Thymeleaf 來作前端模版引擎。javascript

Thymeleaf 介紹

簡單說,Thymeleaf 是一個跟 Velocity、FreeMarker 相似的模板引擎,它能夠徹底替代 JSP 。相較與其餘的模板引擎,它有以下三個極吸引人的特色:html

  • 1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可讓美工在瀏覽器查看頁面的靜態效果,也可讓程序員在服務器查看帶數據的動態頁面效果。這是因爲它支持 html 原型,而後在 html 標籤裏增長額外的屬性來達到模板+數據的展現方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,因此 Thymeleaf 的模板能夠靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。前端

  • 2.Thymeleaf 開箱即用的特性。它提供標準和 Spring 標準兩種方言,能夠直接套用模板實現 JSTL、 OGNL表達式效果,避免天天套模板、該 Jstl、改標籤的困擾。同時開發人員也能夠擴展和建立自定義的方言。java

  • 3.Thymeleaf 提供 Spring 標準方言和一個與 SpringMVC 完美集成的可選模塊,能夠快速的實現表單綁定、屬性編輯器、國際化等功能。git

標準表達式語法

它們分爲四類:程序員

  • 1.變量表達式github

  • 2.選擇或星號表達式web

  • 3.文字國際化表達式面試

  • 4.URL 表達式spring

變量表達式

變量表達式即 OGNL 表達式或 Spring EL 表達式(在 Spring 術語中也叫 model attributes)。以下所示:
${session.user.name}

它們將以HTML標籤的一個屬性來表示:

  1. <span th:text="${book.author.name}">

  2. <li th:each="book : ${books}">

選擇(星號)表達式

選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執行,以下:
*{customer.name}

被指定的 object 由 th:object 屬性定義:

  1. <div th:object="${book}">

  2. ...

  3. <span th:text="*{title}">...</span>

  4. ...

  5. </div>

文字國際化表達式

文字國際化表達式容許咱們從一個外部文件獲取區域文字信息(.properties),用 Key 索引 Value,還能夠提供一組參數(可選).

  1. #{main.title}

  2. #{message.entrycreated(${entryId})}

能夠在模板文件中找到這樣的表達式代碼:

  1. <table>

  2. ...

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

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

  5. ...

  6. </table>

URL 表達式

URL 表達式指的是把一個有用的上下文或回話信息添加到 URL,這個過程常常被叫作 URL 重寫。
@{/order/list}

URL還能夠設置參數:
@{/order/details(id=${orderId})}

相對路徑:
@{../documents/report}

讓咱們看這些表達式:

  1. <form th:action="@{/createOrder}">

  2. <a href="main.html" th:href="@{/main}">

變量表達式和星號表達有什麼區別嗎?

若是不考慮上下文的狀況下,二者沒有區別;星號語法評估在選定對象上表達,而不是整個上下文
什麼是選定對象?就是父標籤的值,以下:

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

  2. <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

  3. <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>

  4. <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

  5. </div>

這是徹底等價於:

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

  2. <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>

  3. <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

  4. <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>

  5. </div>

固然,美圓符號和星號語法能夠混合使用:

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

  2. <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

  3. <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

  4. <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

  5. </div>

表達式支持的語法

字面(Literals)

  • 文本文字(Text literals): 'one text','Another one!',…

  • 數字文本(Number literals): 0,34,3.0,12.3,…

  • 布爾文本(Boolean literals): true,false

  • 空(Null literal): null

  • 文字標記(Literal tokens): one,sometext,main,…

文本操做(Text operations)

  • 字符串鏈接(String concatenation): +

  • 文本替換(Literal substitutions): |Thenameis${name}|

算術運算(Arithmetic operations)

  • 二元運算符(Binary operators): +,-,*,/,%

  • 減號(單目運算符)Minus sign (unary operator): -

布爾操做(Boolean operations)

  • 二元運算符(Binary operators): and,or

  • 布爾否認(一元運算符)Boolean negation (unary operator): !,not

比較和等價(Comparisons and equality)

  • 比較(Comparators): >,<,>=,<=(gt,lt,ge,le)

  • 等值運算符(Equality operators): ==,!=(eq,ne)

條件運算符(Conditional operators)

  • If-then: (if)?(then)

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

  • Default: (value) ?: (defaultvalue)

全部這些特徵能夠被組合並嵌套:

  1. 'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

經常使用th標籤都有那些?

關鍵字 功能介紹 案例
th:id 替換id <inputth:id="'xxx' + ${collect.id}"/>
th:text 文本替換 <pth:text="${collect.description}">description</p>
th:utext 支持html的文本替換 <pth:utext="${htmlcontent}">conten</p>
th:object 替換對象 <divth:object="${session.user}">
th:value 屬性賦值 <inputth:value="${user.name}"/>
th:with 變量賦值運算 <divth: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 判斷條件 <ath:if="${userId == collect.userId}">
th:unless 和th:if判斷相反 <ath:href="@{/login}"th:unless=${session.user!=null}>Login</a>
th:href 連接地址 <ath:href="@{/login}"th:unless=${session.user!=null}>Login</a>/>
th:switch 多路選擇 配合th:case 使用 <divth:switch="${user.role}">
th:case th:switch的一個分支 <pth:case="'admin'">User is an administrator</p>
th:fragment 佈局標籤,定義一個代碼片斷,方便其它地方引用 <divth:fragment="alert">
th:include 佈局標籤,替換內容到引入的文件 <headth:include="layout :: htmlhead"th:with="title='xx'"></head>/>
th:replace 佈局標籤,替換整個標籤到引入的文件 <divth:replace="fragments/header :: title"></div>
th:selected selected選擇框 選中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 圖片類地址引入 <imgclass="img-responsive"alt="App Logo"th:src="@{/img/logo.png}"/>
th:inline 定義js腳本可使用變量 <scripttype="text/javascript"th:inline="javascript">
th:action 表單提交的地址 <formaction="subscribe.html"th:action="@{/subscribe}">
th:remove 刪除某個屬性 <trth:remove="all">1.all:刪除包含標籤和全部的孩子。2.body:不包含標記刪除,但刪除其全部的孩子。3.tag:包含標記的刪除,但不刪除它的孩子。4.all-but-first:刪除全部包含標籤的孩子,除了第一個。5.none:什麼也不作。這個值是有用的動態評估。
th:attr 設置標籤屬性,多個屬性能夠用逗號分隔 好比 th:attr="src=@{/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

幾種經常使用的使用方法

一、賦值、字符串拼接

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

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

字符串拼接還有另一種簡潔的寫法

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

二、條件判斷 If/Unless

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

  1. <a th:if="${myself=='yes'}" > </i> </a>

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

th:unless 於 th:if 剛好相反,只有表達式中的條件不成立,纔會顯示其內容。

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

三、for 循環

  1. <tr th:each="collect,iterStat : ${collects}">

  2. <th scope="row" th:text="${collect.id}">1</th>

  3. <td >

  4. <img th:src="${collect.webLogo}"/>

  5. </td>

  6. <td th:text="${collect.url}">Mark</td>

  7. <td th:text="${collect.title}">Otto</td>

  8. <td th:text="${collect.description}">@mdo</td>

  9. <td th:text="${terStat.index}">index</td>

  10. </tr>

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 等屬性,下面是一個例子

  1. <!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->

  2. <a th:href="@{/standard/{type}(type=${type})}">view</a>

  3.  

  4. <!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->

  5. <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

設置背景

  1. <div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

根據屬性值改變背景

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

幾點說明:

  • 上例中 URL 最後的 (orderId=${o.id})表示將括號內的內容做爲 URL 參數處理,該語法避免使用字符串拼接,大大提升了可讀性

  • @{...}表達式中能夠經過 {orderId}訪問 Context 中的 orderId 變量

  • @{/order}是 Context 相關的相對路徑,在渲染時會自動添加上當前 Web 應用的 Context 名字,假設 context 名字爲 app,那麼結果應該是 /app/order

五、內聯 js

內聯文本:[[...]] 內聯文本的表示方式,使用時,必須先用 th:inline="text/javascript/none"激活, th:inline能夠在父級標籤內使用,甚至做爲 body 的標籤。內聯文本儘管比 th:text的代碼少,不利於原型顯示。

  1. <script th:inline="javascript">

  2. /*<![CDATA[*/

  3. ...

  4. var username = /*[[${sesion.user.name}]]*/ 'Sebastian';

  5. var size = /*[[${size}]]*/ 0;

  6. ...

  7. /*]]>*/

  8. </script>

js 附加代碼:

  1. /*[+

  2. var msg = 'This is a working application';

  3. +]*/

js 移除代碼:

  1. /*[- */

  2. var msg = 'This is a non-working template';

  3. /* -]*/

六、內嵌變量

爲了模板更加易用,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

  1. /*

  2. * Format date with the specified pattern

  3. * Also works with arrays, lists or sets

  4. */

  5. ${#dates.format(date, 'dd/MMM/yyyy HH:mm')}

  6. ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}

  7. ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}

  8. ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}

  9.  

  10. /*

  11. * Create a date (java.util.Date) object for the current date and time

  12. */

  13. ${#dates.createNow()}

  14.  

  15. /*

  16. * Create a date (java.util.Date) object for the current date (time set to 00:00)

  17. */

  18. ${#dates.createToday()}

strings

  1. /*

  2. * Check whether a String is empty (or null). Performs a trim() operation before check

  3. * Also works with arrays, lists or sets

  4. */

  5. ${#strings.isEmpty(name)}

  6. ${#strings.arrayIsEmpty(nameArr)}

  7. ${#strings.listIsEmpty(nameList)}

  8. ${#strings.setIsEmpty(nameSet)}

  9.  

  10. /*

  11. * Check whether a String starts or ends with a fragment

  12. * Also works with arrays, lists or sets

  13. */

  14. ${#strings.startsWith(name,'Don')} // also array*, list* and set*

  15. ${#strings.endsWith(name,endingFragment)} // also array*, list* and set*

  16.  

  17. /*

  18. * Compute length

  19. * Also works with arrays, lists or sets

  20. */

  21. ${#strings.length(str)}

  22.  

  23. /*

  24. * Null-safe comparison and concatenation

  25. */

  26. ${#strings.equals(str)}

  27. ${#strings.equalsIgnoreCase(str)}

  28. ${#strings.concat(str)}

  29. ${#strings.concatReplaceNulls(str)}

  30.  

  31. /*

  32. * Random

  33. */

  34. ${#strings.randomAlphanumeric(count)}

使用 Thymeleaf 佈局

Spring Boot 2.0 將佈局單獨提取了出來,須要單獨引入依賴:thymeleaf-layout-dialect。

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>

  4. </dependency>

  5. <dependency>

  6. <groupId>nz.net.ultraq.thymeleaf</groupId>

  7. <artifactId>thymeleaf-layout-dialect</artifactId>

  8. </dependency>

定義代碼片斷

  1. <footer th:fragment="copy">

  2. &copy; 2019

  3. </footer>

在頁面任何地方引入:

  1. <body>

  2. <div th:insert="layout/copyright :: copyright"></div>

  3. <div th:replace="layout/copyright :: copyright"></div>

  4. </body>

th:insert 和 th:replace 區別,insert 只是加載,replace 是替換。Thymeleaf 3.0 推薦使用 th:insert 替換 2.0 的 th:replace。

返回的 HTML 以下:

  1. <body>

  2. <div> &copy; 2019 </div>

  3. <footer>&copy; 2019 </footer>

  4. </body>

下面是一個經常使用的後臺頁面佈局,將整個頁面分爲頭部,尾部、菜單欄、隱藏欄,點擊菜單隻改變 content 區域的頁面

  1. <body class="layout-fixed">

  2. <div th:fragment="navbar" class="wrapper" role="navigation">

  3. <div th:replace="fragments/header :: header">Header</div>

  4. <div th:replace="fragments/left :: left">left</div>

  5. <div th:replace="fragments/sidebar :: sidebar">sidebar</div>

  6. <div layout:fragment="content" id="content" ></div>

  7. <div th:replace="fragments/footer :: footer">footer</div>

  8. </div>

  9. </body>

任何頁面想使用這樣的佈局值只須要替換中見的 content 模塊便可

  1. <html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout">

  2. <body>

  3. <section layout:fragment="content">

  4. ...

也能夠在引用模版的時候傳參

  1. <head th:include="layout :: htmlhead" th:with="title='Hello'"></head>

layout 是文件地址,若是有文件夾能夠這樣寫 fileName/layout:htmlhead,htmlhead 是指定義的代碼片斷 如 th:fragment="copy"

文章示例項目

示例代碼-https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-thymeleaf

文章內容已經升級到 Spring Boot 2.x

精彩回顧:

面試點:Java 中 hashCode() 和 equals() 的關係

容器鏈接[Docker 系列-7]

現現在的技術浪潮中,咱們到底該作些什麼?

 

強烈推薦:

《Java 極客技術》知識星球限時優惠,如今加入只需 50 元,僅限前 1000 名,機不可失時再也不來。趁早行動吧!

https://t.zsxq.com/J6Em2nU

 

隆重介紹:

Java 極客技術公衆號,是由一羣熱愛 Java 開發的技術人組建成立,專一分享原創、高質量的 Java 文章。若是您以爲咱們的文章還不錯,請幫忙讚揚、在看、轉發支持,鼓勵咱們分享出更好的文章。

 

相關文章
相關標籤/搜索