模板引擎 Thymeleaf

如何識別Thymeleaf標準方言

<span th:text="...">
#需引入命名空間
<span data-th-text="...">
#不需要引入命名空間

變量表達式

語法: ${…}

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

消息表達式

也稱爲文本外部化、國際化或i18n
語法:#{…}

選擇表達式

語法:*{…}

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

與變量表達式區別:它們是在當前選擇的對象而不是整個上下文變量映射上執行

鏈接表達式

語法:@{…}
鏈接表達式可以是相對的,在這種情況下,應用程序上下文將不會作爲URL的前綴

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

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

<a th:href="@{~/documents/report}">...</a>

和協議相對(就像絕對URL,但瀏覽器將使用在顯示的頁面中使用的相同的HTTP或HTTPS協議)

<a th:href="@{//static.mycompany.com/res/initial}">...</a>

當然,Link表達式可以是絕對的:

<a th:href="@{http://www.mycompany.com/res/initial}">...</a>

分段表達式

語法:th:insert 或 th:replace

字面量(文字)

文本

<span th:text="'working web application'"></span>

數字

<span th:text="2019+1"></span>

布爾

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

null

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

算術操作

如 + - * / %

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

比較和等價

、 <、 >=、 <=、 (gt、 lt、 ge、 le)
==、 !=、 (eq、 ne)

條件運算符

<tr th:class="${row.even} ? 'even' : 'odd'">
	...
</tr>

無操作

_ (下劃線)

	<span th:text="${user.name] ?  :  _">no user authenticated</span>
	#用戶不存在,什麼都不做

設置屬性值

設置任意屬性值 th:attr

<form action="subscribe.html" th:attr="action=@{/subscribe}">
	<fieldset>
			<input type="text" name="email"/>
			<input type="submit" value="Subscrbe!" th:attr="value=#{subscribe.submit}"/>
		</fieldset>
</form>

設置值到指定的屬性

<form action="subscribe.html" th:action="@{/subscribe}">
	<fieldset>
			<input type="text" name="email"/>
			<input type="submit" value="Subscrbe!" th:value="#{subscribe.submit}"/>
		</fieldset>
</form>

固定值布爾屬性

<input type="checkbox" name="option2" checked/>
thymeleaf表示爲
<input type="checkbox" name="option2" th:checked="${user.active}"/>
#如果user.active爲false,checked就不顯示了

迭代

基本的迭代 th:each

<li th:each="book : ${books}" th:text="${book.title}"> en las Orillas del Sar</li>

數組、List、Map

狀態變量

  • index、 count、 size、 current、 even/odd、 first 、last

條件語句

th:if 、th:unless

<span th:if="${not #lists.isEmpty(prod.comments)}">view</span>

<span th:unless="${lists.isEmpty(prod.comments)}">view</span>

switch

<div th:switch=${user.role}>
	<p th:case="'admin'"> User is an administrator</p>
	<p th:case="#{roles.manager}"> User is a manager</p>
	<p th:case="*"> User is some other thing</p>
</div>

模板佈局

定義片段

footer.html

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		<div th:fragment="copy">
			&copy; 2019 <a href='http://www.giteasy.cn'> giteasy.cn</a>
		</div>
	</body>
</html>

不使用th:fragment

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		<div id="copy-section">
			&copy; 2019 <a href='http://www.giteasy.cn'> giteasy.cn</a>
		</div>
	</body>
</html>

引用片段

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		...
		<div th:insert="~{footer :: copy}">
		</div>
	</body>
</html>

引用未使用th:fragment定義的片段

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		...
		<div th:insert="~{footer :: #copy-section}">
		</div>
	</body>
</html>

th:insert、 th:replace 、th:include三者區別

  • th:insert它將簡單地插入指定的片段作爲正文的主標籤。
  • th:replace用指定實際片段來替換其主標籤。
  • th:include類似於th:insert,但不是插入片段它只插入此片段的內容。(3.x版本後,不再推薦使用)

屬性優先級

<ul>
<li th:each="item : ${items}" th:text="${item.description}">Item description here ... </li>
</ul>

th:each 與 th:text書寫順序不影響代碼的執行

優先級

Order Feature Attributes
1 Fragment inclusion th:insert th:replace
2 Fragment iteration th:each
3 Conditional evaluation th:if th:unless th:switch th:case
4 Local variable definition th:object th:with
5 General attribute modification th:attr th:attrprepend th:attrappend
6 Specific attribute modification th:value th:href th:src …
7 Text(tag body modification) th:text th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

註釋

標準HTML/XML註釋

<!-- User info follows -->
<div th:text="${...}"> 
	...
</div>

Thymeleaf 解析器級註釋塊

刪除 之間的所有內容

<!--/* -->
<div th:text="${...}"> 
	...
</div>
<!-- */-->

原型註釋塊

當模板靜態打開時(比如原型設計),原型註釋 塊所註釋的代碼將被註釋,不顯示。而在模版執行時,這些註釋的代碼,就能被顯示出來。與解析器級註釋塊意義相反。

<span>hello!</span>
	<!--/*/
		<div th:text="${...}"> 
		...
		</div>
	/*/-->
<span>goodbye!</span>

內聯

內聯表達式

[[…]] 或 [(…)] 分別對應於th:text和th:utext

<p>The message is "[(${msg})]"</p>
執行後顯示爲
<p>The message is "This is <b>great!</b>"</p>
<p>The message is "[[${msg}]]"</p>
執行後顯示爲
<p>The message is "This is &lt;b&gt;great!&lt;/b&gt;"</p>

禁用內聯 th:inline

有時需要禁用這種機制,比如,想輸出[[…]]或[(…)]文本內容

<p th:inline="none"> A double array looks like this: [[1,2,3],[4,5]]!</p>

JavaScript內聯

<script th:inline="javascript">
	...
	var username = /*[[${session.user.name}]]*/ "gertrud Kiwifruit";
	...
</script>

執行後

<script th:inline="javascript">
	...
	var username = "Sebastian \"Fruity\" Applejuice";
	...
</script>

CSS內聯

classname = 'main elems'
align = 'center'
<style th:inline="css">
	.[[${classname}]] {
		text-align:[[${align}]];
	}
</style>

執行後

<style th:inline="css">
	.main elems{
		text-align:center;
	}
</style>

表達式基本對象

基本對象

  • #ctx:上下文對象。是org.thymeleaf.context.IContext或者org.thymeleaf.context.IWebContext的實現
  • #locale: 直接訪問與java.util.Locale關聯的當前的請求
/*
*===========================================
* See javadoc API for class org.thymeleaf.context.IContext
*===========================================
*/
${#ctx.locale}
${#ctx.variableNames}


/*
*===========================================
* See javadoc API for class org.thymeleaf.context.IWebContext
*===========================================
*/

${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}

${#locale}

request/session等屬性

  • param:用於檢索請求參數
  • session:用於檢索session屬性
  • application:用於檢索application/servlet上下文屬性
/*
*===========================================
* See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap
*===========================================
*/
${param.foo}
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}

/*
*===========================================
* See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap
*===========================================
*/
${session.foo}
${session.size()}
${session.isEmpty()}
${session.containsKey('foo')}

/*
*===========================================
 * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap
*===========================================
*/
${application.foo}
${application.size()}
${application.isEmpty()}
${application.containsKey('foo')}

Web上下文對象

  • #request: 直接訪問與當前請求關聯的javax.servlet.http.HttpServletRequest對象
  • #session: 直接訪問與當前請求關聯的javax.servlet.http.HttpSession對象
  • #servletContext: 直接訪問與當前請求關聯的javax.servlet.ServletContext對象
${#request.getAttribute('foo')}
${#request.getParameter('foo')}
${#request.getContextPath()}
${#request.getRequestName()}
...

${#session.getAttribute('foo')}
${#session.id}
${#session.lastAccessedTime}

...
${#servletContext.getAttribute('foo')}
${#servletContext.contextPath()}

thymeleaf Maven依賴


<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.2.0</version>
</dependency>

github地址:https://github.com/gitAxin/thymeleaf-in-action.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章