thymeleaf介紹
thymeleaf 是新一代的模板引擎,在spring4.0中推薦使用thymeleaf來做前端模版引擎。簡單說是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個極吸引人的特點:
- thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
- thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。
- thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
添加Maven依賴
在pom.xml文件中添加spring-boot-starter-thymeleaf依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置application.properties
#端口號
server.port=80
#訪問路徑
server.context-path=/
#編碼
spring.thymeleaf.encoding=UTF-8
#返回模板類型
spring.thymeleaf.servlet.content-type=text/html
#開發時關閉緩存,不然沒法看到實時頁面
spring.thymeleaf.cache=false
# 在構建URL時預先查看名稱的前綴 (默認就是這個)
spring.thymeleaf.prefix=classpath:/templates/
# 構建URL時附加查看名稱的後綴.(默認就是 html的結尾的)
spring.thymeleaf.suffix=.html
標準表達式語法
- 變量表達式
- 選擇或星號表達式
- 文字國際化表達式
- URL表達式
1. 變量表達式
變量表達式即OGNL表達式或Spring EL表達式(在Spring術語中也叫model attributes) 它們將以HTML標籤的一個屬性來表示:
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
2. 選擇(星號)表達式
選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執行,被指定的object由th:object
屬性定義:
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
3. 文字國際化表達式
文字國際化表達式允許我們從一個外部文件獲取區域文字信息(.properties),用Key-value的形式配置國際化信息(此文不做示例)
4. URL表達式
URL表達式指的是把一個有用的上下文或回話信息添加到URL,這個過程經常被叫做URL重寫。 @{/order/list}
URL還可以設置參數:@{/order/details(id=${orderId})}
相對路徑:@{../documents/report}
讓我們看這些表達式:
<form th:action="@{/createOrder}"></form>
<a th:href="@{/main}"></a>
變量表達式和星號表達有什麼區別嗎 ?
如果不考慮上下文的情況下,兩者沒有區別;星號語法評估在選定對象上表達,而不是整個上下文。 什麼是選定對象?就是父標籤的值,如下:
<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>
當然,美元符號和星號語法可以混合使用:
<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>
表達式支持的語法
字面(Literals)
文本文字(Text literals): ‘one text’, ‘Another one!’,…
數字文本(Number literals): 0, 34, 3.0, 12.3,…
布爾文本(Boolean literals): true, false
空(Null literal): null
文字標記(Literal tokens): one, sometext, main,…
文本操作(Text operations)
字符串連接(String concatenation): +
文本替換(Literal substitutions): |The name is ${name}|
算術運算(Arithmetic operations)
二元運算符(Binary operators): +, -, *, /, %
減號(單目運算符)Minus sign (unary operator): -
布爾操作(Boolean operations)
二元運算符(Binary operators):and, or
布爾否定(一元運算符)Boolean negation (unary operator):!, not
比較和等價(Comparisons and equality)
比較(Comparators): >, =, <= (gt, lt, ge, le)
等值運算符(Equality operators):==, != (eq, ne)
條件運算符(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'))
幾種常用的使用方法
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
屬性進行條件判斷,下面的例子中,標籤只有在th:if
中條件成立時才顯示:
<a th:if="${myself=='yes'}" >baidu</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>
iterStat稱作狀態變量,屬性有:
- index:當前迭代對象的index(從0開始計算)
- count: 當前迭代對象的index(從1開始計算)
- size:被迭代對象的大小
- current:當前迭代變量
- even/odd:布爾值,當前循環是否是偶數/奇數(從0開始計算)
- first:布爾值,當前循環是否是第一個
- last:布爾值,當前循環是否是最後一個
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
thymeleaf中的內聯[[ ]]
- 文本內聯
[[…]]
之間的表達式在Thymeleaf被認爲是內聯表達式,在其中您可以使用任何類型的表達式,也會有效th:text
屬性。
<p>Hello, [[${session.user.name}]]!</p>
等同於:
<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>
爲了讓內聯工作,我們必須激活它使用th:inline
屬性,它有三個可能的值或模式(text, javascript 和 none)。讓我們試着文本:
<p th:inline="text">Hello, [[${session.user.name}]]!</p>
如果不使用th:inline="text"
,則會被當做字符串顯示。th:inline="javascript"
表示能在js中使用[[ ]]
取值。 標籤的th:inline
不需要包含內聯的一個表達式,任何父標籤都行,例如如下也是可以的:
<body th:inline="text">
...
<p>Hello, [[${session.user.name}]]!</p>
...
</body>
- 腳本內聯
Thymeleaf提供一系列的 “腳本” 的內聯模式功能,這樣你就可以將你的數據在腳本中創建一些腳本語言。 我們可以做的第一件事,寫腳本內聯表達式的值到我們的腳本。
<script th:inline="javascript">
var user = [[${user.username}]];
alert(user);
</script>
<script th:inline="javascript">
var msg = 'Hello, ' + [[${user.username}]];
alert(msg);
</script>
只要加入th:inline="javascript"
在js代碼中才能使用[[ ]]
內嵌變量
爲了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),可以通過#直接訪問:
- dates : java.util.Date的功能方法類
- calendars : 類似#dates,面向java.util.Calendar
- numbers : 格式化數字的功能方法類
- strings : 字符串對象的功能類,contains,startWiths,prepending/appending等等
- objects: 對objects的功能類操作
- bools: 對布爾值求值的功能方法
- arrays:對數組的功能類方法
- 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佈局
使用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 :: header" th:with="title='Hello'"></head>
layout 是文件地址,如果有文件夾可以這樣寫dir/layout header是指定義的代碼片段,如:th:fragment="copy"