溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot中Thymeleaf使用方法有哪些

發(fā)布時(shí)間:2022-01-07 09:49:50 來(lái)源:億速云 閱讀:154 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Spring Boot中Thymeleaf使用方法有哪些”,在日常操作中,相信很多人在Spring Boot中Thymeleaf使用方法有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Spring Boot中Thymeleaf使用方法有哪些”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

Thymeleaf 介紹

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

  • 1.Thymeleaf 在有網(wǎng)絡(luò)和無(wú)網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁(yè)面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動(dòng)態(tài)頁(yè)面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來(lái)達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會(huì)忽略未定義的標(biāo)簽屬性,所以 Thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁(yè)面時(shí),Thymeleaf 標(biāo)簽會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。

  • 2.Thymeleaf 開箱即用的特性。它提供標(biāo)準(zhǔn)和 Spring 標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn) JSTL、 OGNL表達(dá)式效果,避免每天套模板、該 Jstl、改標(biāo)簽的困擾。同時(shí)開發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。

  • 3.Thymeleaf 提供 Spring 標(biāo)準(zhǔn)方言和一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。

標(biāo)準(zhǔn)表達(dá)式語(yǔ)法

它們分為四類:

  • 1.變量表達(dá)式

  • 2.選擇或星號(hào)表達(dá)式

  • 3.文字國(guó)際化表達(dá)式

  • 4.URL 表達(dá)式

變量表達(dá)式

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

它們將以HTML標(biāo)簽的一個(gè)屬性來(lái)表示:

<span th:text="${book.author.name}">  <li th:each="book : ${books}">

選擇(星號(hào))表達(dá)式

選擇表達(dá)式很像變量表達(dá)式,不過它們用一個(gè)預(yù)先選擇的對(duì)象來(lái)代替上下文變量容器(map)來(lái)執(zhí)行,如下:
*{customer.name}

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

<div th:object="${book}">    ...    <span th:text="*{title}">...</span>    ...  </div>

文字國(guó)際化表達(dá)式

文字國(guó)際化表達(dá)式允許我們從一個(gè)外部文件獲取區(qū)域文字信息(.properties),用 Key 索引 Value,還可以提供一組參數(shù)(可選).

#{main.title}  #{message.entrycreated(${entryId})}

可以在模板文件中找到這樣的表達(dá)式代碼:

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

URL 表達(dá)式

URL 表達(dá)式指的是把一個(gè)有用的上下文或回話信息添加到 URL,這個(gè)過程經(jīng)常被叫做 URL 重寫。
@{/order/list}

URL還可以設(shè)置參數(shù):
@{/order/details(id=${orderId})}

相對(duì)路徑:
@{../documents/report}

讓我們看這些表達(dá)式:

<form th:action="@{/createOrder}">  <a href="main.html" th:href="@{/main}">

變量表達(dá)式和星號(hào)表達(dá)有什么區(qū)別嗎?

如果不考慮上下文的情況下,兩者沒有區(qū)別;星號(hào)語(yǔ)法評(píng)估在選定對(duì)象上表達(dá),而不是整個(gè)上下文
什么是選定對(duì)象?就是父標(biāo)簽的值,如下:

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

這是完全等價(jià)于:

<div th:object="${session.user}">  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p></div>

當(dāng)然,美元符號(hào)和星號(hào)語(yǔ)法可以混合使用:

  <div th:object="${session.user}">      <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>        <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>      <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>  </div>

表達(dá)式支持的語(yǔ)法

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

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

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

  • 空(Null literal): null

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

文本操作(Text operations)
  • 字符串連接(String concatenation): +

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

算術(shù)運(yùn)算(Arithmetic operations)
  • 二元運(yùn)算符(Binary operators): +,-,*,/,%

  • 減號(hào)(單目運(yùn)算符)Minus sign (unary operator): -

布爾操作(Boolean operations)
  • 二元運(yùn)算符(Binary operators): and,or

  • 布爾否定(一元運(yùn)算符)Boolean negation (unary operator): !,not

比較和等價(jià)(Comparisons and equality)
  • 比較(Comparators): >,<,>=,<=(gt,lt,ge,le)

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

條件運(yùn)算符(Conditional operators)
  • If-then: (if)?(then)

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

  • Default: (value) ?: (defaultvalue)

所有這些特征可以被組合并嵌套:

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

常用th標(biāo)簽都有那些?

關(guān)鍵字功能介紹案例
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替換對(duì)象<divth:object="${session.user}">
th:value屬性賦值<inputth:value="${user.name}"/>
th:with變量賦值運(yùn)算<divth:with="isEven=${prodStat.count}%2==0"></div>
th:style設(shè)置樣式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick點(diǎn)擊事件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:caseth:switch的一個(gè)分支<pth:case="'admin'">User is an administrator</p>
th:fragment布局標(biāo)簽,定義一個(gè)代碼片段,方便其它地方引用<divth:fragment="alert">
th:include布局標(biāo)簽,替換內(nèi)容到引入的文件<headth:include="layout :: htmlhead"th:with="title='xx'"></head>/>
th:replace布局標(biāo)簽,替換整個(gè)標(biāo)簽到引入的文件<divth:replace="fragments/header :: title"></div>
th:selectedselected選擇框 選中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刪除某個(gè)屬性<trth:remove="all">1.all:刪除包含標(biāo)簽和所有的孩子。2.body:不包含標(biāo)記刪除,但刪除其所有的孩子。3.tag:包含標(biāo)記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標(biāo)簽的孩子,除了第一個(gè)。5.none:什么也不做。這個(gè)值是有用的動(dòng)態(tài)評(píng)估。
th:attr設(shè)置標(biāo)簽屬性,多個(gè)屬性可以用逗號(hào)分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此標(biāo)簽不太優(yōu)雅,一般用的比較少。

還有非常多的標(biāo)簽,這里只列出最常用的幾個(gè),由于一個(gè)標(biāo)簽內(nèi)可以包含多個(gè)th:x屬性,其生效的優(yōu)先級(jí)順序?yàn)? 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><span th:text="'Welcome to our application, ' + ${user.name} + '!'">

字符串拼接還有另外一種簡(jiǎn)潔的寫法

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

2、條件判斷 If/Unless

Thymeleaf中使用th:if和th:unless屬性進(jìn)行條件判斷,下面的例子中, <a>標(biāo)簽只有在 th:if中條件成立時(shí)才顯示:

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

th:unless 于 th:if 恰好相反,只有表達(dá)式中的條件不成立,才會(huì)顯示其內(nèi)容。

也可以使用 (if)?(then):(else)這種語(yǔ)法來(lái)判斷顯示的內(nèi)容

3、for 循環(huán)

<tr  th:each="collect,iterStat : ${collects}">    <th scope="row" th:text="${collect.id}">1</th>   <td >      <img th:src="${collect.webLogo}"/>   </td>   <td th:text="${collect.url}">Mark</td>   <td th:text="${collect.title}">Otto</td>   <td th:text="${collect.description}">@mdo</td>   <td th:text="${terStat.index}">index</td></tr>

iterStat稱作狀態(tài)變量,屬性有:

  • index:當(dāng)前迭代對(duì)象的 index(從0開始計(jì)算)

  • count: 當(dāng)前迭代對(duì)象的 index(從1開始計(jì)算)

  • size:被迭代對(duì)象的大小

  • current:當(dāng)前迭代變量

  • even/odd:布爾值,當(dāng)前循環(huán)是否是偶數(shù)/奇數(shù)(從0開始計(jì)算)

  • first:布爾值,當(dāng)前循環(huán)是否是第一個(gè)

  • last:布爾值,當(dāng)前循環(huán)是否是最后一個(gè)

4、URL

URL 在 Web 應(yīng)用模板中占據(jù)著十分重要的地位,需要特別注意的是 Thymeleaf 對(duì)于 URL 的處理是通過語(yǔ)法 @{...} 來(lái)處理的。 如果需要 Thymeleaf 對(duì) URL 進(jìn)行渲染,那么務(wù)必使用 th:href, th:src 等屬性,下面是一個(gè)例子

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

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


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

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

設(shè)置背景

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

根據(jù)屬性值改變背景

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

幾點(diǎn)說(shuō)明:

  • 上例中 URL 最后的 (orderId=${o.id})表示將括號(hào)內(nèi)的內(nèi)容作為 URL 參數(shù)處理,該語(yǔ)法避免使用字符串拼接,大大提高了可讀性

  • @{...}表達(dá)式中可以通過 {orderId}訪問 Context 中的 orderId 變量

  • @{/order}是 Context 相關(guān)的相對(duì)路徑,在渲染時(shí)會(huì)自動(dòng)添加上當(dāng)前 Web 應(yīng)用的 Context 名字,假設(shè) context 名字為 app,那么結(jié)果應(yīng)該是 /app/order

5、內(nèi)聯(lián) js

內(nèi)聯(lián)文本:[[...]] 內(nèi)聯(lián)文本的表示方式,使用時(shí),必須先用 th:inline="text/javascript/none"激活, th:inline可以在父級(jí)標(biāo)簽內(nèi)使用,甚至作為 body 的標(biāo)簽。內(nèi)聯(lián)文本盡管比 th:text的代碼少,不利于原型顯示。

<script th:inline="javascript">/*<![CDATA[*/...var username = /*[[${sesion.user.name}]]*/ 'Sebastian';var size = /*[[${size}]]*/ 0;.../*]]>*/</script>

js 附加代碼:

/*[+var msg = 'This is a working application';+]*/

js 移除代碼:

/*[- */var msg = 'This is a non-working template';/* -]*/

6、內(nèi)嵌變量

為了模板更加易用,Thymeleaf 還提供了一系列 Utility 對(duì)象(內(nèi)置于 Context 中),可以通過 # 直接訪問:

  • dates : java.util.Date的功能方法類。

  • calendars : 類似#dates,面向java.util.Calendar

  • numbers : 格式化數(shù)字的功能方法類

  • strings : 字符串對(duì)象的功能類,contains,startWiths,prepending/appending等等。

  • objects: 對(duì)objects的功能類操作。

  • bools: 對(duì)布爾值求值的功能方法。

  • arrays:對(duì)數(shù)組的功能類方法。

  • lists: 對(duì)lists功能類方法

  • sets

  • maps
    ...

下面用一段代碼來(lái)舉例一些常用的方法:

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. * Create a date (java.util.Date) object for the current date and time

  11. */

  12. ${#dates.createNow()}


  13. /*

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

  15. */

  16. ${#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. * Check whether a String starts or ends with a fragment

  11. * Also works with arrays, lists or sets

  12. */

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

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


  15. /*

  16. * Compute length

  17. * Also works with arrays, lists or sets

  18. */

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


  20. /*

  21. * Null-safe comparison and concatenation

  22. */

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

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

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

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


  27. /*

  28. * Random

  29. */

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

使用 Thymeleaf 布局

Spring Boot 2.0 將布局單獨(dú)提取了出來(lái),需要單獨(dú)引入依賴:thymeleaf-layout-dialect。

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency>    <groupId>nz.net.ultraq.thymeleaf</groupId>    <artifactId>thymeleaf-layout-dialect</artifactId></dependency>

定義代碼片段

<footer th:fragment="copy"> &copy; 2019</footer>

在頁(yè)面任何地方引入:

<body>    <div th:insert="layout/copyright :: copyright"></div>    <div th:replace="layout/copyright :: copyright"></div></body>

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

返回的 HTML 如下:

<body>    <div> &copy; 2019 </div>   <footer>&copy; 2019 </footer> </body>

下面是一個(gè)常用的后臺(tái)頁(yè)面布局,將整個(gè)頁(yè)面分為頭部,尾部、菜單欄、隱藏欄,點(diǎn)擊菜單只改變 content 區(qū)域的頁(yè)面

<body class="layout-fixed">  <div th:fragment="navbar"  class="wrapper"  role="navigation">    <div th:replace="fragments/header :: header">Header</div>    <div th:replace="fragments/left :: left">left</div>    <div th:replace="fragments/sidebar :: sidebar">sidebar</div>    <div layout:fragment="content" id="content" ></div>    <div th:replace="fragments/footer :: footer">footer</div>  </div></body>

任何頁(yè)面想使用這樣的布局值只需要替換中見的 content 模塊即可

<html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout"> <body>    <section layout:fragment="content">  ...

也可以在引用模版的時(shí)候傳參

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

layout 是文件地址,如果有文件夾可以這樣寫 fileName/layout:htmlhead,htmlhead 是指定義的代碼片段 如 th:fragment="copy"

到此,關(guān)于“Spring Boot中Thymeleaf使用方法有哪些”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI