spring boot 中用到的thymeleaf (模板引擎)
???????????????????????????? ??thymeleaf
?
一.??????????簡要:
thymeleaf 支持html5標準;是一種模板引擎框架(TemplateEngine Framework);thymeleaf 頁面無須部署到servlet開發到服務器上,直接通過瀏覽器就能打開。它可以完全替代 JSP 。特點:
-
1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由于它支持 html 原型,然后在 html 標簽里增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標簽屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標簽會動態地替換掉靜態內容,使頁面動態顯示。
-
2.它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果。
-
3.Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
二.??????????thymeleaf 標準表達式語法
1.??????簡單表達式
(1)??????Variable Expressions(變量表達式):${…}。
EX: ${session.user.name}
它們將以HTML標簽的一個屬性來表示:
<span th:text="${book.author.name}"> <li th:each="book : ${books}">變量表達式可以是OGNL表達式或Spring EL表達式。
<span th:text="${book.author.name}"> <li th:each="book : ${books}">這里${books}從上下文中選擇名為books的變量,并將其評估為可在th:each循環中使用的迭代器(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(選擇表達式):*{…}。
EX:? *{customer.name}????????
(所有可用值表達式:比如*{name} 從可用值中查找name,如果有上下文,比如上層是object,則查object中的name屬性。)
?
所作用的對象由th:object屬性指定。
EX:
equals:(等價于)
(3)??????Message(il8n)Expressions(消息表達式):#{…}。
文字國際化表達式允許我們從一個外部文件獲取區域文字信息(.properties),用Key索引Value,還可以提供一組參數(可選).
國際化時使用,也可以使用內置的對象,比如date格式化數據
EX:
<table> ... <th th:text="#{header.address.city}">...</th> <th th:text="#{header.address.country}">...</th> ... </table> #{main.title} #{message.entrycreated(${entryId})}注意:如果希望消息key由上下文變量的值確定,或者將變量指定為參數,則可以在消息表達式中使用變量表達式。
(4)??????Link(URL)Expressions(鏈接表達式):@{…}。
URL表達式指的是把一個有用的上下文或回話信息添加到URL,這個過程經常被叫做URL重寫。
?@{/order/list}?
URL還可以設置參數:
?@{/order/details(id=${orderId})}??
相對路徑:
?@{../documents/report}?
EX:
鏈接表達式可以是相對的,在這種情況下,應用程序上下文將不會作為URL的前綴。
<a th:href=”@{../documents/report}”>…</a>
也可以是服務器相對(同樣,沒有應用程序上下文前綴)
<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(分段表達式):~{…}。
分段表達式是一種表示標記片段并將其移動到模板周圍的簡單方法。
最常見的用法是使用th:insert或th:replace插入片段。
?
2.??????字面量
(1)??????文本:’one text’ ’Another one!’等。
?<div th:class=" ‘the content’ ">...</div>
(2)??????數值: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(字面量標記):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.??????算數操作
(1)??????二元運算符:+、- 、* 、/、%。
(2)??????減號(單目運算符):—。
<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)??????二元運算符:and、or。
(2)??????布爾否定(一元運算符):!、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.? 條件運算符
?(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.特殊標記
No-Operation(無操作):_。
9.表達式基本對象(Expression Basic Objects)
(1)#ctx:上下文對象。
(2)#vars: 上下文變量。
(3)#locale:上下文區域設置。
(4)#request:HttpServletRequest對象(僅在Web上下文中)。
(5)#response:HttpServletResponse對象(僅在Web上下文中)。
(6)#session:HttpSession對象(僅在Web上下文中)。
(7)#servletContext:ServletContext對象(僅在Web上下文中)。
10.表達式工具對象(ExpressionUtility Objects)
(1)#execInfo:模板執行的信息。
(2)#message:在變量內獲取外部信息的方法表達式,與使用#{…}語法獲得的方式相同。
(3)#uris:用于轉義URL/URI部分的方法。
(4)#conversions:執行已配置的conversion service。
(5)#numbers:格式化數字對象的方法。
(6)#strings:String對象的方法,包括contains,startsWith,prepending/appending等。
(7)#objects:對象通常方法。
(8)#bools:布爾判斷的方法。
(10)#lists:list方法。
(11)#sets:set方法。
(12)#maps:map方法。
(13)#aggregates:在數組或集合上創建聚合的方法。
(14)#ids:用于處理可能重復的id屬性的方法(如作為迭代的結果)。
常用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="src=@{/image/aa.jpg},title=#{logo}",此標簽不太優雅,一般用的比較少。 |
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設置屬性值:
(1)th:text
可對表達式或變量求值,并將結果顯示在其被包含的 html 標簽體內替換原有html文本
文本鏈接: 用 “+”符號,若是變量表達式也可以用“|”符號.
(2)th:utext
e.g.
若home.welcome=Welcome to our <b>fantastic</b> grocery store!
?? 用<p th:text="#{home.welcome}"></p>解析結果為:
?? <p>Welcome to our <b>fantastic</b> grocery store!</p>
解決方案
<p th:utext="#{home.welcome}"></p>即可。
等效于<p>Welcome to our <b>fantastic</b> grocery store!</p>
(3)th:href
@{xxx} :鏈接url的表達式
th: attr 用于設置任意屬性。
th: value用于設置value屬性值。
?
th:action設置action屬性。
?
2.????同時設置多個值
?
th:alt-title用于設置alt和title。
?
th:lang-xmllang用于設置lang和xml:lang。
?
3.?????附加和添加前綴
?
th:attrappend和th:attrprepend用于附加和添加前綴屬性。
?
4.?????固定值布爾屬性
四.迭代器(iter)與條件語句
1.th:each將循環array或list中的元素并重復打印一組標簽,語法相當于Java foreach表達式。
可以用th:each屬性進行遍歷的對象如下。
(1)????? 任何實現Java.util.Iterable的對象。
(2)????? 任何實現Java.util.Enumeration的對象。
(3)????? 任何實現Java.util.Iterator的對象,其值將被迭代器返回,而不需要在內存中緩存所有的值。
(4)????? 任何實現Java.util.Map的對象。迭代映射時,迭代變量將是Java.util.Map.Entry類。
(5)????? 任何數組。
(6)????? 任何其他對象將被視為包含對象本身的單值列表。
2.狀態變量
提供狀態變量來跟蹤迭代器狀態。
判斷操作(實例)
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">優</td><td th:if="${test.Score} gt 90 and ${test.Score} le 100">超級優秀</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>?
?結果顯示:
差?
中?
超級優秀
差?
及格?
及格
男?
女
th:each屬性中定義如下狀態變量。
(1)????? index屬性是當前“迭代器引擎”,從0開始。
(2)????? count屬性是當前“迭代器索引”,從1開始。
(3)????? size 屬性是迭代器元素的總數。
(4)????? current 是當前“迭代變量”。
(5)????? even/odd判斷當前迭代器是否為even或odd。
(6)????? first判斷當前迭代器是否為第一個。
(7)????? last判斷當前迭代器是否為最后。
3.條件語句
(1)if和unless
支持下列規則判斷:
<1>值不為null:
? ? ?<1.1>布爾類型且為true;
?????????? <1.2>非0數字;
? ? ? <1.3>非0字符;
?????????? <1.4>非“false”, “off” or “no”字符串;
?????????? <1.5>判斷值不為布爾值,數字,字符,字符串
????????? 結果為true
<2>值為null,結果為false
(2)switch語句
Switch語句使用th:switch與th:case屬性集合來實現。
一旦有一個th:case對應結果為true,其他均為false;
默認值語法為:? 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屬性進行條件判斷,下面的例子中,<a>標簽只有在th:if中條件成立時才顯示:
<a th:if="${myself=='yes'}" > </i> </a> <a th:unless=${session.user != null} th:href="@{/login}" >Login</a>th:unless于th:if恰好相反,只有表達式中的條件不成立,才會顯示其內容。
也可以使用?(if) ? (then) : (else)?這種語法來判斷顯示的內容
3、for 循環
<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>?
渲染列表數據是一種非常常見的場景,例如現在有n條記錄需要渲染成一個表格
,該數據集合必須是可以遍歷的,使用th:each標簽:
<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>可以看到,需要在被循環渲染的元素(這里是)中加入th:each標簽,其中th:each=”prod : ${prods}”意味著對集合變量prods進行遍歷,循環變量是prod在循環體中可以通過表達式訪問。
?
循環下標判
iterStat稱作狀態變量,屬性有:
- index:當前迭代對象的index(從0開始計算)
- count: 當前迭代對象的index(從1開始計算)
- size:被迭代對象的大小
- current:當前迭代變量
- even/odd:布爾值,當前循環是否是偶數/奇數(從0開始計算)
- first:布爾值,當前循環是否是第一個
- last:布爾值,當前循環是否是最后一個
- <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應用模板中占據著十分重要的地位,需要特別注意的是Thymeleaf對于URL的處理是通過語法@{…}來處理的。 如果需要Thymeleaf對URL進行渲染,那么務必使用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>設置背景
<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>根據屬性值改變背景
<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
5、內聯js
內聯文本:[[…]]內聯文本的表示方式,使用時,必須先用th:inline=”text/javascript/none”激活,th:inline可以在父級標簽內使用,甚至作為body的標簽。內聯文本盡管比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、內嵌變量
為了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置于Context中),可以通過#直接訪問:
?下面用一段代碼來舉例一些常用的方法:
?dates
?
- dates :?java.util.Date的功能方法類。
- calendars :?類似#dates,面向java.util.Calendar
- numbers :?格式化數字的功能方法類
- strings :?字符串對象的功能類,contains,startWiths,prepending/appending等等。
- objects:?對objects的功能類操作。
- bools:?對布爾值求值的功能方法。
- arrays:對數組的功能類方法。
- lists:?對lists功能類方法
- sets
- maps
…
?
五.thymeleaf模板片段
1.定義和引用片段
(1)定義片段屬性用:?? th:fragment
fragment片段定義語法:
如th:fragment=”copy”這樣就定義了一個名為copy的fragment.
模板操作
主要引入公共頭部和底部相關代碼使用 ,當然也可以其他地方使用?
- 示例
底部模板代碼
<!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的內容包含進來;
th:replace:用fragment替換掉所在標簽
(2)引用片段?? th:insert 或 th:replace 屬性
(3)th:include 類似于th:insert 但不是插入片段,它只插入此片段的”內容“。
注:th:insert 需要一個”片段表達式”(~{…})
th:remove
? 一般用于將模擬數據在真實環境中移除:
?? <1>all-移除標簽及標簽內容
?? <2>body-只移除內容
?? <3>tag-只移除所在標簽
?? <4>all-but-first-除第一條外移除所有內容
?? <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"> © 2016 </footer>在頁面任何地方引入:
<body> <div th:include="footer :: copy"></div><div th:replace="footer :: copy"></div></body>th:include 和 th:replace區別,include只是加載,replace是替換
返回的HTML如下:
<body> <div> © 2016 </div> <footer>© 2016 </footer> </body>下面是一個常用的后臺頁面布局,將整個頁面分為頭部,尾部、菜單欄、隱藏欄,點擊菜單只改變content區域的頁面
<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"
六.表達式基本對象
1.基本對象
(1)#ctx:上下文對象。
(2)#locale:直接訪問與java.util.Locale關聯的當前的請求。
2.web上下文命名空間
(1)param:用于檢索請求參數。
(2)session:用于檢索會話屬性。
(3)application:用于檢索應用及上下文屬性。
3.web上下文對象
(1)#request:直接訪問與當前請求關聯的javax.servlet.http.HttpServletRequest對象。
(2)#session:直接訪問與當前請求關聯的javax.servlet.http.HttpSession對象。
(3)#servletContext:直接訪問與當前請求關聯的javax.servlet.ServletContext對象。
七.模板注釋
1.標準 HTML/XML注釋
??語法:<!--???? -->??
? 2.解析器級注釋塊(Parser-level comment blocks)
???? 語法:<!--/*??? */-->
????? thymeleaf解析時會移除代碼
???? 單行:<!--/*? xxxxx? */-->
???? 雙行:
?????????? <!--/*-->
?????????? Xxxxxx
?????????? Xxxxxx
????????? <!--*/-->
3.針對原型的注釋
語法:<!--/*/??? /*/-->
thymealeaf解析時會移除掉此標簽對,但不會移除其中的內容。
4.與th:block結合
thymealeaf解析時會移除掉此標簽對,但不會移除其中的內容。
內聯
[[...]]是內聯文本的表示格式,但需要使用th:inline屬性(分為text,javascript,none)激活.
1.文本內聯
??? <p th:inline="text">Hello, [[${session.user.name}]]!</p>
?? 2.腳本內聯
???? <script th:inline="javascript">
????? /*<![CDATA[*/
???????? ...
??????? var username = /*[[${session.user.name}]]*/ 'Sebastian';
??????? ...
????? /*]]>*/
???? </script>
Note:
1.腳本注釋/* */中的內容會在瀏覽器端靜態打開頁面時被忽略;
2.thymeleaf解析模板時會把后面的文本'Sebastian'移除.
javascript內聯時特性
<1>javascript附加代碼
語法:/*[+?? +]*/?
/*[+
var msg? = 'This is a working application';
+]*/
<2>javascript移除代碼
語法:/*[- */??? /* -]*/
/*[- */
var msg? = 'This is a non-working template';
/* -]*/
?
?
總結
以上是生活随笔為你收集整理的spring boot 中用到的thymeleaf (模板引擎)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux性能监控工具perf,Linu
- 下一篇: 小学生计算机教室注意事项,小学生安全注意