日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot 中用到的thymeleaf (模板引擎)

發(fā)布時間:2024/3/13 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot 中用到的thymeleaf (模板引擎) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

???????????????????????????? ??thymeleaf

?

一.??????????簡要:

thymeleaf 支持html5標(biāo)準(zhǔn);是一種模板引擎框架(TemplateEngine Framework);thymeleaf 頁面無須部署到servlet開發(fā)到服務(wù)器上,直接通過瀏覽器就能打開。它可以完全替代 JSP 。特點(diǎn):

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

  • 2.它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn)JSTL、 OGNL表達(dá)式效果。

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

二.??????????thymeleaf 標(biāo)準(zhǔn)表達(dá)式語法

1.??????簡單表達(dá)式

(1)??????Variable Expressions(變量表達(dá)式):${…}。

EX: ${session.user.name}

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

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

變量表達(dá)式可以是OGNL表達(dá)式或Spring EL表達(dá)式。

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

這里${books}從上下文中選擇名為books的變量,并將其評估為可在th:each循環(huán)中使用的迭代器(iterable)

e.g.

1.Established locale country: <spanth:text="${#locale.country}">US</span>

2.<p>? Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span></p>

(2)??????Selection Expressions(選擇表達(dá)式):*{…}。

EX:? *{customer.name}????????

(所有可用值表達(dá)式:比如*{name} 從可用值中查找name,如果有上下文,比如上層是object,則查object中的name屬性。)

?

所作用的對象由th:object屬性指定。

EX

equals:(等價于)

(3)??????Message(il8n)Expressions(消息表達(dá)式):#{…}。

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

國際化時使用,也可以使用內(nèi)置的對象,比如date格式化數(shù)據(jù)

EX:

<table> ... <th th:text="#{header.address.city}">...</th> <th th:text="#{header.address.country}">...</th> ... </table> #{main.title} #{message.entrycreated(${entryId})}

注意:如果希望消息key由上下文變量的值確定,或者將變量指定為參數(shù),則可以在消息表達(dá)式中使用變量表達(dá)式。

(4)??????Link(URL)Expressions(鏈接表達(dá)式):@{…}

URL表達(dá)式指的是把一個有用的上下文或回話信息添加到URL,這個過程經(jīng)常被叫做URL重寫。
?@{/order/list}?
URL還可以設(shè)置參數(shù):
?@{/order/details(id=${orderId})}??
相對路徑:
?@{../documents/report}?

EX:

鏈接表達(dá)式可以是相對的,在這種情況下,應(yīng)用程序上下文將不會作為URL的前綴。

<a th:href=”@{../documents/report}”>…</a>

也可以是服務(wù)器相對(同樣,沒有應(yīng)用程序上下文前綴)

<a th:href=”@{~/contents/main}”>…</a>

e.g.

<a???? th:href="@{http://www.thymeleaf/documentation.html}"></a>

equals:

<a href="http://www.thymeleaf/documentation.html"></a>

?

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

(5)??????Fragment Expressions(分段表達(dá)式):~{…}。

分段表達(dá)式是一種表示標(biāo)記片段并將其移動到模板周圍的簡單方法。

最常見的用法是使用th:insert或th:replace插入片段。

?

2.??????字面量

(1)??????文本:’one text’ ’Another one!’等。

?<div th:class=" ‘the content’ ">...</div>

(2)??????數(shù)值:0、34、3.0、12.3等。

ex:? ??<p>The year is <span th:text="2013">1492</span>.</p>

(3)??????布爾:true、false。

ex: <div th:if="${user.isAdmin()} == false">

ex: <div th:if="${user.isAdmin() == false}">

(4)??????null :null。

ex:? <div th:if="${variable.something} == null">

(5)??????Literal Token(字面量標(biāo)記):one、sometext、main等。

ex: 

<div th:class="content">...</div>

3.??????文本操作

(1)??????字符串拼接:+。

(2)??????文本替換:| The name is ${name} |。

ex:

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

4.??????算數(shù)操作

(1)??????二元運(yùn)算符:+、- 、* 、/、%。

(2)??????減號(單目運(yùn)算符):—。

<ol><li>+:<span th:text="1+1">1+1</span>.</li><li>-: <span th:text="2-1">2-1</span>.</li><li>*:<span th:text="2*3">2*3</span>.</li><li>/: <span th:text="9/4">9/4</span>.</li><li>%:<span th:text="9%4">9%4</span>.</li> </ol>

5.??????布爾操作

(1)??????二元運(yùn)算符:and、or。

(2)??????布爾否定(一元運(yùn)算符):!、not。

<ol> <li>and:<span th:if="${!#lists.isEmpty(list)} and ${#lists.isEmpty(list)}" th:text="${!#lists.isEmpty(list)} and ${#lists.isEmpty(list)}">and</span></li> <li>or:<span th:if="${!#lists.isEmpty(list)} or ${#lists.isEmpty(list)}" th:text="${!#lists.isEmpty(list)} or ${#lists.isEmpty(list)}">or</span></li> <li>!(not):<span th:if="${!#lists.isEmpty(list)}" th:text="${!#lists.isEmpty(list)}">not</span></li> </ol>

6.??????比較和等價

(1)???? 比較:>、<、>=、<=、(gt,lt,ge,le)。

(2)????? 等價:==、!=、(eq、ne)。

<ol><li>>(gt):<span th:text="1+1" th:if="${#lists.size(list)} > 1">大于></span>else</li><li>小于lt:<span th:if="${#lists.size(list)} lt 1">小于</span>else</li><li>>=(ge):<span th:if="${#lists.size(list)} >= 1">大于等于>=</span>else</li><li>小于等于(le):<span th:if="${#lists.size(list)} le 1">小于等于</span>else</li><li>!(not):<span th:if="${!#lists.isEmpty(list)}">!(not)</span>else</li><li>==(eq):<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">等于==</span></li><li>!=(ne/neq):size:<span th:text="${#lists.size(list)}" th:if="${#lists.size(list)} != 1"></span></li> </ol>

7.? 條件運(yùn)算符

?(1)If-then:(if) ? (then)。

(2)If-then-else:(if) ? (then) : (else)。

(3)Default:(value) ? (default value)。

<li>? 'xx' :'xx'(if ? then:else)<span th:class="${title} ? 'green' :' red'">樣例一</span></li> <li>?'xx'(if ? then)<span th:class="${title1} ? 'green'">樣例二</span></li>

8.特殊標(biāo)記

No-Operation(無操作):_。

9.表達(dá)式基本對象(Expression Basic Objects)

(1)#ctx:上下文對象。

(2)#vars: 上下文變量。

(3)#locale:上下文區(qū)域設(shè)置。

(4)#request:HttpServletRequest對象(僅在Web上下文中)。

(5)#response:HttpServletResponse對象(僅在Web上下文中)。

(6)#session:HttpSession對象(僅在Web上下文中)。

(7)#servletContext:ServletContext對象(僅在Web上下文中)。

10.表達(dá)式工具對象(ExpressionUtility Objects)

(1)#execInfo:模板執(zhí)行的信息。

(2)#message:在變量內(nèi)獲取外部信息的方法表達(dá)式,與使用#{…}語法獲得的方式相同。

(3)#uris:用于轉(zhuǎn)義URL/URI部分的方法。

(4)#conversions:執(zhí)行已配置的conversion service。

(5)#numbers:格式化數(shù)字對象的方法。

(6)#strings:String對象的方法,包括contains,startsWith,prepending/appending等。

(7)#objects:對象通常方法。

(8)#bools:布爾判斷的方法。

(10)#lists:list方法。

(11)#sets:set方法。

(12)#maps:map方法。

(13)#aggregates:在數(shù)組或集合上創(chuàng)建聚合的方法。

(14)#ids:用于處理可能重復(fù)的id屬性的方法(如作為迭代的結(jié)果)。

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

關(guān)鍵字功能介紹案例
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變量賦值運(yùn)算<div th: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判斷條件?<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:caseth:switch的一個分支?<p th:case="'admin'">User is an administrator</p>
th:fragment布局標(biāo)簽,定義一個代碼片段,方便其它地方引用<div th:fragment="alert">
th:include布局標(biāo)簽,替換內(nèi)容到引入的文件<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />?
th:replace布局標(biāo)簽,替換整個標(biāo)簽到引入的文件<div th:replace="fragments/header :: title"></div>?
th:selectedselected選擇框 選中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:刪除包含標(biāo)簽和所有的孩子。2.body:不包含標(biāo)記刪除,但刪除其所有的孩子。3.tag:包含標(biāo)記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標(biāo)簽的孩子,除了第一個。5.none:什么也不做。這個值是有用的動態(tài)評估。
th:attr設(shè)置標(biāo)簽屬性,多個屬性可以用逗號分隔比如?th:attr="src=@{/image/aa.jpg},title=#{logo}",此標(biāo)簽不太優(yōu)雅,一般用的比較少。

html5的操作支持:

th:abbr th:accept th:accept-charset th:accesskey th:action th:align th:alt th:archive th:audio th:autocomplete th:axis th:background th:bgcolor th:border th:cellpadding th:cellspacing th:challenge th:charset th:cite th:class th:classid th:codebase th:codetype th:cols th:colspan th:compact th:content th:contenteditable th:contextmenu th:data th:datetime th:dir th:draggable th:dropzone th:enctype th:for th:form th:formaction th:formenctype th:formmethod th:formtarget th:fragment th:frame th:frameborder th:headers th:height th:high th:href th:hreflang th:hspace th:http-equivth:icon th:id th:inline th:keytype th:kind th:label th:lang th:list th:longdesc th:low th:manifest th:marginheight th:marginwidth th:max th:maxlength th:media th:method th:min th:name th:onabort th:onafterprint th:onbeforeprint th:onbeforeunload th:onblur th:oncanplay th:oncanplaythrough th:onchange th:onclick th:oncontextmenu th:ondblclick th:ondrag th:ondragend th:ondragenter th:ondragleave th:ondragover th:ondragstart th:ondrop th:ondurationchange th:onemptied th:onended th:onerror th:onfocus th:onformchange th:onforminput th:onhashchange th:oninput th:oninvalid th:onkeydown th:onkeypress th:onkeyup th:onload th:onloadeddata th:onloadedmetadata th:onloadstart th:onmessage th:onmousedown th:onmousemove th:onmouseout th:onmouseover th:onmouseup th:onmousewheel th:onoffline th:ononline th:onpause th:onplay th:onplaying th:onpopstate th:onprogress th:onratechange th:onreadystatechange th:onredo th:onreset th:onresize th:onscroll th:onseeked th:onseeking th:onselect th:onshow th:onstalled th:onstorage th:onsubmit th:onsuspend th:ontimeupdate th:onundo th:onunload th:onvolumechange th:onwaiting th:optimum th:pattern th:placeholder th:poster th:preload th:radiogroup th:rel th:rev th:rows th:rowspan th:rules th:sandbox th:scheme th:scope th:scrolling th:size th:sizes th:span th:spellcheck th:src th:srclang th:standby th:start th:step th:style th:summary th:tabindex th:target th:title th:type th:usemap th:value th:valuetype th:vspace th:width th:wrapth:vspace th:width th:wrap th:xmlbase th:xmllang th:xmlspace

布爾類型

th:async th:autofocus th:autoplay th:checked th:controls th:declare th:default th:defer th:disabled th:formnovalidate th:hidden th:ismap th:loop th:multiple th:novalidate th:nowrap th:open th:pubdate th:readonly th:required th:reversed th:scoped th:seamless th:selected

?

三.???? ?thymeleaf設(shè)置屬性值:

(1)th:text

可對表達(dá)式或變量求值,并將結(jié)果顯示在其被包含的 html 標(biāo)簽體內(nèi)替換原有html文本

文本鏈接: 用 “+”符號,若是變量表達(dá)式也可以用“|”符號.

(2)th:utext

e.g.

若home.welcome=Welcome to our <b>fantastic</b> grocery store!

?? 用<p th:text="#{home.welcome}"></p>解析結(jié)果為:

?? <p>Welcome to our &lt;b&gt;fantastic&lt;/b&gt; grocery store!</p>

解決方案

<p th:utext="#{home.welcome}"></p>即可。

等效于<p>Welcome to our <b>fantastic</b> grocery store!</p>

(3)th:href

@{xxx} :鏈接url的表達(dá)式

th: attr 用于設(shè)置任意屬性。

th: value用于設(shè)置value屬性值。

?

th:action設(shè)置action屬性。

?

2.????同時設(shè)置多個值

?

th:alt-title用于設(shè)置alt和title。

?

th:lang-xmllang用于設(shè)置lang和xml:lang。

?

3.?????附加和添加前綴

?

th:attrappend和th:attrprepend用于附加和添加前綴屬性。

?

4.?????固定值布爾屬性

四.迭代器(iter)與條件語句

1.th:each將循環(huán)array或list中的元素并重復(fù)打印一組標(biāo)簽,語法相當(dāng)于Java foreach表達(dá)式。

可以用th:each屬性進(jìn)行遍歷的對象如下。

(1)????? 任何實(shí)現(xiàn)Java.util.Iterable的對象。

(2)????? 任何實(shí)現(xiàn)Java.util.Enumeration的對象。

(3)????? 任何實(shí)現(xiàn)Java.util.Iterator的對象,其值將被迭代器返回,而不需要在內(nèi)存中緩存所有的值。

(4)????? 任何實(shí)現(xiàn)Java.util.Map的對象。迭代映射時,迭代變量將是Java.util.Map.Entry類。

(5)????? 任何數(shù)組。

(6)????? 任何其他對象將被視為包含對象本身的單值列表。

2.狀態(tài)變量

提供狀態(tài)變量來跟蹤迭代器狀態(tài)。

判斷操作(實(shí)例)

thymeleaf提供了幾種判斷,if、switch

<table><thead><th></th></thead><tbody><tr th:each="test:${test}"><!--判斷成績--><td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td><td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td><td th:if="${test.Score} gt 70 and ${test.Score} le 80">良</td><td th:if="${test.Score} gt 80 and ${test.Score} le 90">優(yōu)</td><td th:if="${test.Score} gt 90 and ${test.Score} le 100">超級優(yōu)秀</td></tr><br><tr th:each="test:${test}"><!--判斷成績 一般只有兩種情況的時候可以使用這種方式--><td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td><!--除了這些條件之外的--><td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td></tr><tr th:each="test:${test}"><td th:switch="${test.male}"><span th:case="1">男</span><span th:case="2">女</span><!--其他情況--><span th:case="*">未知</span></td></tr></tbody></table>

?

?結(jié)果顯示:

差?
中?
超級優(yōu)秀

差?
及格?
及格

男?

th:each屬性中定義如下狀態(tài)變量。

(1)????? index屬性是當(dāng)前“迭代器引擎”,從0開始。

(2)????? count屬性是當(dāng)前“迭代器索引”,從1開始。

(3)????? size 屬性是迭代器元素的總數(shù)。

(4)????? current 是當(dāng)前“迭代變量”。

(5)????? even/odd判斷當(dāng)前迭代器是否為even或odd。

(6)????? first判斷當(dāng)前迭代器是否為第一個。

(7)????? last判斷當(dāng)前迭代器是否為最后。

3.條件語句

(1)if和unless

支持下列規(guī)則判斷

<1>值不為null

? ? ?<1.1>布爾類型且為true;

?????????? <1.2>非0數(shù)字;

? ? ? <1.3>非0字符;

?????????? <1.4>非“false”, “off” or “no”字符串;

?????????? <1.5>判斷值不為布爾值,數(shù)字,字符,字符串

????????? 結(jié)果為true

<2>值為null,結(jié)果為false

(2)switch語句

Switch語句使用th:switch與th:case屬性集合來實(shí)現(xiàn)。

一旦有一個th:case對應(yīng)結(jié)果為true,其他均為false;

默認(rèn)值語法為:? th:case=”*”

幾種常用的使用方法

1、賦值、字符串拼接

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

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

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

2、條件判斷 If/Unless

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

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

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

也可以使用?(if) ? (then) : (else)?這種語法來判斷顯示的內(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>

?

渲染列表數(shù)據(jù)是一種非常常見的場景,例如現(xiàn)在有n條記錄需要渲染成一個表格

,該數(shù)據(jù)集合必須是可以遍歷的,使用th:each標(biāo)簽:

<body><h1>Product list</h1><table><tr><th>NAME</th><th>PRICE</th><th>IN STOCK</th></tr><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></table><p><a href="../home.html" th:href="@{/}">Return to home</a></p> </body>

可以看到,需要在被循環(huán)渲染的元素(這里是)中加入th:each標(biāo)簽,其中th:each=”prod : ${prods}”意味著對集合變量prods進(jìn)行遍歷,循環(huán)變量是prod在循環(huán)體中可以通過表達(dá)式訪問。

?

循環(huán)下標(biāo)判

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

  • index:當(dāng)前迭代對象的index(從0開始計算)
  • count: 當(dāng)前迭代對象的index(從1開始計算)
  • size:被迭代對象的大小
  • current:當(dāng)前迭代變量
  • even/odd:布爾值,當(dāng)前循環(huán)是否是偶數(shù)/奇數(shù)(從0開始計算)
  • first:布爾值,當(dāng)前循環(huán)是否是第一個
  • last:布爾值,當(dāng)前循環(huán)是否是最后一個
  • <th:block th:each="mylist,iterStat:${list}">111<span th:text="${mylist}"></span><th:block th:if="${iterStat.index le 1}"><span th:text="${mylist}"></span></th:block> </th:block>

?

下拉選擇

<select name="subId" id="subId" lay-verify="" ><option value="">請選擇</option><option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}" th:value="${channelsub.id}" th:text="${channelsub.name}"></option></select>

?

4、URL

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

<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) --><a th:href="@{/standard/{type}(type=${type})}">view</a><!-- Will produce '/gtvg/order/3/details' (plus rewriting) --> <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)說明:

  • 上例中URL最后的(orderId=${o.id})?表示將括號內(nèi)的內(nèi)容作為URL參數(shù)處理,該語法避免使用字符串拼接,大大提高了可讀性
  • @{...}表達(dá)式中可以通過{orderId}訪問Context中的orderId變量
  • @{/order}是Context相關(guān)的相對路徑,在渲染時會自動添加上當(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)文本的表示方式,使用時,必須先用th:inline=”text/javascript/none”激活,th:inline可以在父級標(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對象(內(nèi)置于Context中),可以通過#直接訪問:

?下面用一段代碼來舉例一些常用的方法:

?dates

?

  • dates :?java.util.Date的功能方法類。
  • calendars :?類似#dates,面向java.util.Calendar
  • numbers :?格式化數(shù)字的功能方法類
  • strings :?字符串對象的功能類,contains,startWiths,prepending/appending等等。
  • objects:?對objects的功能類操作。
  • bools:?對布爾值求值的功能方法。
  • arrays:對數(shù)組的功能類方法。
  • lists:?對lists功能類方法
  • sets
  • maps
/** Format date with the specified pattern* Also works with arrays, lists or sets*/ ${#dates.format(date, 'dd/MMM/yyyy HH:mm')} ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')} ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')} ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}/** Create a date (java.util.Date) object for the current date and time*/ ${#dates.createNow()}/** Create a date (java.util.Date) object for the current date (time set to 00:00)*/ ${#dates.createToday()} /** Check whether a String is empty (or null). Performs a trim() operation before check* Also works with arrays, lists or sets*/ ${#strings.isEmpty(name)} ${#strings.arrayIsEmpty(nameArr)} ${#strings.listIsEmpty(nameList)} ${#strings.setIsEmpty(nameSet)}/** Check whether a String starts or ends with a fragment* Also works with arrays, lists or sets*/ ${#strings.startsWith(name,'Don')} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set*/** Compute length* Also works with arrays, lists or sets*/ ${#strings.length(str)}/** Null-safe comparison and concatenation*/ ${#strings.equals(str)} ${#strings.equalsIgnoreCase(str)} ${#strings.concat(str)} ${#strings.concatReplaceNulls(str)}/** Random*/ ${#strings.randomAlphanumeric(count)}

?

五.thymeleaf模板片段

1.定義和引用片段

(1)定義片段屬性用:?? th:fragment

fragment片段定義語法

如th:fragment=”copy”這樣就定義了一個名為copy的fragment

模板操作

主要引入公共頭部和底部相關(guān)代碼使用 ,當(dāng)然也可以其他地方使用?
- 示例

底部模板代碼

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <body> <div th:fragment="footer">? 2016 xxx </div> </body> </html>

Springboot整合引入模塊

<!--寫入絕對路徑即可引入 --> <div th:include="/back/import/footer :: footer"></div>

?

th:include:將fragment的內(nèi)容包含進(jìn)來

th:replace:用fragment替換掉所在標(biāo)簽

(2)引用片段?? th:insert 或 th:replace 屬性

(3)th:include 類似于th:insert 但不是插入片段,它只插入此片段的”內(nèi)容“。

注:th:insert 需要一個”片段表達(dá)式”(~{…})

th:remove

? 一般用于將模擬數(shù)據(jù)在真實(shí)環(huán)境中移除

?? <1>all-移除標(biāo)簽及標(biāo)簽內(nèi)容

?? <2>body-只移除內(nèi)容

?? <3>tag-只移除所在標(biāo)簽

?? <4>all-but-first-除第一條外移除所有內(nèi)容

?? <5>none-donothing.

th:width

定義局部變量

1.可一次定義多個,逗號分隔

外圍包裹–block

有時候需要在代碼外部加層條件,但寫div之類的又影響樣式,此情況下你可以用下面這種方式:

<th:block th:with="score=${test.Score}"><td th:if="${score} ge 60">及格啦</td></th:block>

使用thymeleaf布局

使用thymeleaf布局非常的方便

定義代碼片段

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

在頁面任何地方引入:

<body> <div th:include="footer :: copy"></div><div th:replace="footer :: copy"></div></body>

th:include 和 th:replace區(qū)別,include只是加載,replace是替換

返回的HTML如下:

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

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

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

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

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

也可以在引用模版的時候傳參

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

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

六.表達(dá)式基本對象

1.基本對象

(1)#ctx:上下文對象。

(2)#locale:直接訪問與java.util.Locale關(guān)聯(lián)的當(dāng)前的請求。

2.web上下文命名空間

(1)param:用于檢索請求參數(shù)。

(2)session:用于檢索會話屬性。

(3)application:用于檢索應(yīng)用及上下文屬性。

3.web上下文對象

(1)#request:直接訪問與當(dāng)前請求關(guān)聯(lián)的javax.servlet.http.HttpServletRequest對象。

(2)#session:直接訪問與當(dāng)前請求關(guān)聯(lián)的javax.servlet.http.HttpSession對象。

(3)#servletContext:直接訪問與當(dāng)前請求關(guān)聯(lián)的javax.servlet.ServletContext對象。

七.模板注釋

1.標(biāo)準(zhǔn) HTML/XML注釋

??語法:<!--???? -->??

? 2.解析器級注釋塊(Parser-level comment blocks)

???? 語法:<!--/*??? */-->

????? thymeleaf解析時會移除代碼

???? 單行:<!--/*? xxxxx? */-->

???? 雙行

?????????? <!--/*-->

?????????? Xxxxxx

?????????? Xxxxxx

????????? <!--*/-->

3.針對原型的注釋

語法:<!--/*/??? /*/-->

thymealeaf解析時會移除掉此標(biāo)簽對,但不會移除其中的內(nèi)容

4.與th:block結(jié)合

thymealeaf解析時會移除掉此標(biāo)簽對,但不會移除其中的內(nèi)容

內(nèi)聯(lián)

[[...]]是內(nèi)聯(lián)文本的表示格式,但需要使用th:inline屬性(分為text,javascript,none)激活.

1.文本內(nèi)聯(lián)

??? <p th:inline="text">Hello, [[${session.user.name}]]!</p>

?? 2.腳本內(nèi)聯(lián)

???? <script th:inline="javascript">

????? /*<![CDATA[*/

???????? ...

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

??????? ...

????? /*]]>*/

???? </script>

Note:

1.腳本注釋/* */中的內(nèi)容會在瀏覽器端靜態(tài)打開頁面時被忽略

2.thymeleaf解析模板時會把后面的文本'Sebastian'移除.

javascript內(nèi)聯(lián)時特性

<1>javascript附加代碼

語法:/*[+?? +]*/?

/*[+

var msg? = 'This is a working application';

+]*/

<2>javascript移除代碼

語法:/*[- */??? /* -]*/

/*[- */

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

/* -]*/

?

?

總結(jié)

以上是生活随笔為你收集整理的spring boot 中用到的thymeleaf (模板引擎)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。