結(jié)合上一章,這次講下thymeleaf的詳細(xì)使用这嚣。
1鸥昏、介紹
簡單說, Thymeleaf 是一個跟 Velocity姐帚、FreeMarker 類似的模板引擎吏垮,它可以完全替代 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.Thymeleaf 開箱即用的特性。它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言畅厢,可以直接套用模板實(shí)現(xiàn)JSTL锤躁、 OGNL表達(dá)式效果,避免每天套模板、該jstl系羞、改標(biāo)簽的困擾。同時開發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言霸琴。
3.Thymeleaf 提供spring標(biāo)準(zhǔn)方言和一個與 SpringMVC 完美集成的可選模塊椒振,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器梧乘、國際化等功能澎迎。
2、標(biāo)準(zhǔn)表達(dá)式語法
- 1选调、變量表達(dá)式
- 2夹供、選擇或星號表達(dá)式
- 3、文字國際化表達(dá)式
- 4仁堪、URL表達(dá)式
變量表達(dá)式
變量表達(dá)式即OGNL表達(dá)式或Spring EL表達(dá)式(在Spring術(shù)語中也叫model attributes)哮洽。如下所示: ${session.user.name}
它們將以HTML標(biāo)簽的一個屬性來表示:
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
選擇(星號)表達(dá)式
選擇表達(dá)式很像變量表達(dá)式,不過它們用一個預(yù)先選擇的對象來代替上下文變量容器(map)來執(zhí)行弦聂,如下: *{customer.name}
被指定的object由th:object屬性定義:
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
文字國際化表達(dá)式
文字國際化表達(dá)式允許我們從一個外部文件獲取區(qū)域文字信息(.properties)鸟辅,用Key索引Value,還可以提供一組參數(shù)(可選).
<table>
...
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
...
URL表達(dá)式
URL表達(dá)式指的是把一個有用的上下文或回話信息添加到URL莺葫,這個過程經(jīng)常被叫做URL重寫匪凉。 @{/order/list}
URL還可以設(shè)置參數(shù): @{/order/details(id=${orderId})}
相對路徑: @{../documents/report}
讓我們看這些表達(dá)式:
<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">
變量表達(dá)式和星號表達(dá)有什么區(qū)別嗎?
如果不考慮上下文的情況下捺檬,兩者沒有區(qū)別再层;星號語法評估在選定對象上表達(dá),而不是整個上下文
什么是選定對象堡纬?就是父標(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>
這是完全等價于:
<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)然,美元符號和星號語法可以混合使用:
<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á)式支持的語法
字面(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): |The name is ${name}|
算術(shù)運(yùn)算(Arithmetic operations)
- 二元運(yùn)算符(Binary operators): +, -, *, /, %
- 減號(單目運(yùn)算符)Minus sign (unary operator): -
布爾操作(Boolean operations)
- 二元運(yùn)算符(Binary operators):and, or
- 布爾否定(一元運(yùn)算符)Boolean negation (unary operator):!, not
比較和等價(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'))
還有非常多的標(biāo)簽隐轩,這里只列出最常用的幾個,由于一個標(biāo)簽內(nèi)可以包含多個th:x屬性饺饭,其生效的優(yōu)先級順序?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} + '!'">
字符串拼接還有另外一種簡潔的寫法
<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 >
![](${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)前迭代對象的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)是否是最后一個
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 : java.util.Date的功能方法類隔心。
- calendars : 類似#dates,面向java.util.Calendar
- numbers : 格式化數(shù)字的功能方法類
- strings : 字符串對象的功能類尚胞,contains,startWiths,prepending/appending等等硬霍。
- objects: 對objects的功能類操作。
- bools: 對布爾值求值的功能方法笼裳。
- arrays:對數(shù)組的功能類方法唯卖。
- lists: 對lists功能類方法
- sets
- maps
- …
下面用一段代碼來舉例一些常用的方法:
dates
/*
* 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()}
strings
/*
* 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布局
定義代碼片段
<footer th:fragment="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> ? 2016 </div>
<footer>? 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">
...
任何頁面想使用這樣的布局值只需要替換中見的 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”
源碼案例
這里有一個開源項(xiàng)目幾乎使用了這里介紹的所有標(biāo)簽和布局法牲,大家可以參考源碼案例