SpringBoot學習記錄(四)——Thymeleaf
什麼是Thymeleaf:
Thymeleaf是一個適用於Web和獨立環境的現代伺服器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文字。
Thymeleaf的主要目標是提供一種優雅且高度可維護的模板建立方式。為實現這一目標,它以自然模板的概念為基礎,將其邏輯注入模板檔案,其方式不會影響模板被用作設計原型。這改善了設計溝通,縮小了設計和開發團隊之間的差距。
Thymeleaf也從一開始就設計了Web標準 - 特別是HTML5 - 允許您建立完全驗證的模板,如果這是您的需要。
實際開發或學習中,有多種模板引擎可供選擇:
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- Mustache
總體上,thymeleaf 相較與其他的模板引擎,它有如下三個特點:
1. Thymeleaf 在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。(當有資料返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。)
2. Thymeleaf 開箱即用的特性。(它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表示式效果。)
3. Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。
標準表示式語法
它們分為四類:
${...} 變量表達式
*{...} 選擇變量表達式
#{...} 訊息表示式
@{...} 連結url表示式
1、變量表達式
在Spring支援MVC的應用程式中,OGNL將被SpringEL取代,但其語法與OGNL的語法非常相似(實際上,對於大多數常見情況來說,完全相同)。
它們將以HTML標籤的一個屬性來表示:
<span th:text="${user.name}">
2、選擇(星號)表示式
變量表達式不僅可以寫成${...}
*{...}
。但是有一個重要的區別:星號語法評估所選物件上的表示式而不是整個上下文。也就是說,只要沒有選定的物件,$和*語法就會完全相同。
被指定的object由th:object屬性定義:
<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>
<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>
當物件選擇到位時,所選物件也可用作$表示式作為#Object
表示式變數:
<div th:object="${session.user}">
<p>Name: <span th:text="${#object.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>
如上所述,如果沒有執行任何物件選擇,則$和*語法是等效的。
<div>
<p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
</div>
3、訊息(i18n)表示式
訊息表示式允許我們從一個外部檔案獲取區域文字資訊(.properties),用Key索引Value,還可以提供一組引數(可選).
#{main.title}
#{message.entrycreated(${entryId})}
可以在模板檔案中找到這樣的表示式程式碼:
<table>
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
</table>
4、URL表示式
URL表示式它們的重要性,我們經常會用到,如下:
@{/user/login}
URL還可以設定引數:
@{/user/list(id=${o.id})}
<a th:href="@{'/delete?id='+${user.id}}">delete</a>
<a th:href="@{'/login?username='+${user.name}+'&password='+${user.password}}">login</a>
另一種表達方式,與上面這一句意思一樣。
<a th:href="@{|/login?username=${user.name}&password=${user.password}|}">login</a>
讓我們看這些表示式:類似的標籤有:th:href
和th:src
<a th:href="@{http://blog.csdn.net}">絕對路徑</a>
<a th:href="@{/}">相對路徑</a>
<a th:href="@{/delete(id=${user.id})}">delete</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,預設訪問static下的css資料夾</a>
表示式支援的語法
字面(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'))
常用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="[email protected]{/image/aa.jpg},title=#{logo}" ,此標籤不太優雅,一般用的比較少。 |
還有非常多的標籤,這裡只列出最常用的幾個,由於一個標籤內可以包含多個th:x屬性,其生效的優先順序順序為: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}!|">
<a th:href="@{|/login?username=${user.name}&password=${user.password}|}">login</a>
2、條件判斷
If/Unless語句:
Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>
標籤只有在th:if
中條件成立時才顯示:
<a th:if="${myself=='yes'}" > </a>
<a th:if="${sex eq '1'}" > </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>
th:unless於th:if恰好相反,只有表示式中的條件不成立,才會顯示其內容。
也可以使用 (if) ? (then) : (else)
這種語法來判斷顯示的內容
switch,case判斷語句:
<div th:swith=${sex}>
<p th:case="1">男</p>
<p th:case="2">女</p>
<p th:case="*">未知</p>
</p>
如果某個case判斷值為true,剩下的case怎被當做是false,“*”表示預設的case,前面的case都不匹配,執行預設的case。
3、遍歷(List)
<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:布林值,當前迴圈是否是最後一個
遍歷Map:
<tr th:each="collect : ${collects}">
<th th:text="${collect.key}}">
<th scope="row" th:text="${collect.value.id}">1</th>
<td ><img th:src="${collect.value.webLogo}"/></td>
<td th:text="${collect.value.url}">Mark</td>
<td th:text="${collect.value.title}">Otto</td>
<td th:text="${collect.value.description}">@mdo</td>
<td th:text="${terStat.value.index}">index</td>
</tr>
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)
內聯文字:[[…]]內聯文字的表示方式,使用時,必須先用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 : 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佈局非常的方便
- th:insert 3.0+版本新加的
- th:replace 2.0+ 3.0+都可用
- th:include 這個在3.0版本已經不建議使用
直接看一下來著官方的例子:
<!-- 有這麼一個html段 -->
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
<!-- 引用html段 -->
<body>
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
</body>
<!-- 最終結果 -->
<body>
<!-- th:insert,div tag內部插入html段 -->
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<!-- th:replace,使用html段直接替換 div tag -->
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<!-- th:include,div tag內部插入html段(僅保留段子元素的內容) -->
<!-- 仔細對比 th:insert 與 th:include的結果 -->
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
</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>
或者:
<div th:fragment="frag (onevar,twovar)">
<p th:text="${onevar}+' - ' +${twovar}">...</p>
</div>
<div th:include="::frag(${value1},${value2})">...</div>
<div th:include="::frag(onevar=${value1},twovalue=${vaule2})"></div>
<div th:include="::frag(twovalue=${vaule2},onevar=${value1})"></div>
layout 是檔案地址,如果有資料夾可以這樣寫 fileName/layout:htmlhead
htmlhead 是指定義的程式碼片段 如 th:fragment="copy"
詳細參考:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf