一、Thymeleaf 介紹
Thymeleaf 是用於 Web 和獨立環境的現代服務器端Java模板引擎。其主要目標是將優雅的自然模板帶到您的開發工作流程中— HTML 能夠在瀏覽器中正確顯示,並且可以作爲靜態原型,從而在開發團隊中實現更強大的協作。
Thymeleaf 有六種模板模式,包括有 HTML,XML,JavaScript,CSS ,TEXT,RAW。
二、基本語法
1. 變量表達式${...}
變量表達式是OGNL表達式。使用方式:th:xxx="${xxx.xxx}"
,例如:
<form action="/test">
<input name="id" th:value="${user.id}"/>
<input name="name" th:value="${user.name}"/>
</form>
<div th:text="helloThymeleaf"></div>
<h3 th:text="${title}"></h3>
<div th:text="${user.name}"></div>
2. 選擇表達式*{...}
選擇表達式 *{...}
需要與 th:object
一同使用,使用方式是首先通過 th:object="${xx.xxx}
獲取對象,然後通過 th:xxxx="*{vvvv}"
獲取對象 xx.xxx
的屬性 vvvv
的值,例如:
<form action="/indexThymeleaf" method="post" th:object="${user}">
<input name="id" th:value="*{id}"/>
<input name="name" th:value="*{name}"/>
<input type="submit" value="submit" />
</form>
後端代碼爲:
@RequestMapping("/indexThymeleaf")
public String indexThymeleaf(Model model, User user) {
model.addAttribute("title", "springboot整合Thymeleaf");
model.addAttribute("user", user);
return "indexThymeleaf";
}
3. 消息 (i18n) 表達式#{...}
消息表達式 #{...}
允許從外部源(如:.properties)文件中檢索特定於語言環境的消息,通過鍵來引用這引用消息。例如:
首先在 src/main/resources/
下創建文件 messages.properties
,SpringBoot 會自動解析該目錄下的該文件,在其中加入 msg = hello
,然後在html 文件中加入下面代碼就可以獲取其值
<div th:text="#{msg}"></div>
注意:文件名必須爲 messages.properties
,否則 Thymeleaf 不能解析渲染 cus.val
的值,頁面顯示爲 ??msg_zh_CN??
。
4. 鏈接 (URL) 表達式@{...}
使用鏈接表達式 @{...}
可以是相對路徑也可是絕對路徑,能夠使用 @{…} 的標籤主要有 th:action
,th:href
,th:src
,依次相當於 action
,href
,src
。例如:
<form th:action="@{/indexThymeleaf}" method="post" th:object="${user}">
<input name="id" th:value="*{id}"/>
<input name="name" th:value="*{name}"/>
<input type="submit" value="submit" />
</form>
<a th:href="@{/indexThymeleaf}">相對路徑</a>
<a th:href="@{https://www.baidu.com/}">絕對路徑</a>
<a th:href="@{/indexThymeleaf(id=id,name=name)}">相對路徑-通過使用()傳參</a>
<a th:href="@{/indexThymeleaf/{id}(id=2)}">相對路徑-通過 restful風格進行參數傳遞</a>
5. 片段表達式~{...}
片段表達式 ~{...}
是一種簡單的方法用來表示標記的片段並將其移動到模板中,常與 th:insert
或 th:replace
來插入片段,其中有三種語法:
~{ viewname }
:表示引入完整頁面
~{ viewname :: selector}
:表示在指定頁面尋找片段 其中selector可爲片段名、jquery選擇器等
~{ :: selector}
:表示在當前頁尋找
例如:
聲明模板片段src/main/resources/templates/test.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body th:fragment="foot">
hello Thymeleaf
</body>
</html>
引入模板片段:
<div th:include="test :: foot"></div>
三、Thymeleaf 內置對象
注意:
- 調用內置對象一定要用
#
- 大部分的內置對象都以 s 結尾 strings、numbers、dates
1. 七大基礎對象
${#ctx}
:上下文對象,可用於獲取其它內置對象${#vars}
:上下文變量${#locale}
:上下文區域設置${#request}
:HttpServletRequest對象${#response}
:HttpServletResponse對象${#session}
:HttpSession對象${#servletContext}
:ServletContext對象
例如:
獲取 request 中的值:
request.setAttribute("req", "HttpServletRequest");
Request:<span th:text="${#httpServletRequest.getAttribute('req')}"></span>
獲取 session 中的值:
request.getSession().setAttribute("sess", "HttpSession");
Session:<span th:text="${session.sess}"></span>
獲取 aervletContext:
request.getSession().getServletContext().setAttribute("app", "Application");
Application:<span th:text="${application.app}"></span>
2. 常用工具對象
#strings
:字符串工具類,常用方法有:isEmpty(key)
,contains(msg,'T')
,length(msg)
,substring(msg,13,15)
#dates
:時間操作和時間格式化等,常用方法:format(key,'yyy/MM/dd')
,year(key)
#numbers
:格式化數字對象的方法#ids
:處理可能重複的id屬性的方法#arrays
:數組工具類#lists
:List 工具類#sets
:Set 工具類#maps
:常用Map方法#objects
:一般對象類,通常用來判斷非空#messages
:在變量表達式中獲取外部消息的方法,與使用#{…}語法獲取的方法相同
四、條件判斷
用於條件判斷主要有 th:if
和 th:unless
,其中 th:unless
表示取反。下面演示它們的用法:
<span th:if="${user.name} == '男'">性別:男</span>
<span th:if="${user.name} == '女'">性別:女</span>
<span th:unless="${user.name} == '女'">性別:男</span>
還有 th:switch
的用法如下:
<div th:switch="${user.id}">
<span th:case="1">ID 爲 1</span>
<span th:case="2">ID 爲 2</span>
<span th:case="3">ID 爲 3</span>
</div>
五、迭代循環
下述實例統一使用一個Controller,主要代碼:
@RequestMapping("/indexThymeleaf")
public String indexThymeleaf(Model model) {
List<User> list = new ArrayList<>();
list.add(new User("1", "zhangsan"));
list.add(new User("2", "lisi"));
list.add(new User("3", "wangwu"));
list.add(new User("4", "趙六"));
model.addAttribute("users", list);
Map<String, User> map = new HashMap<>();
map.put("11", new User("1", "zhangsan"));
map.put("12", new User("2", "lisi"));
map.put("13", new User("3", "wangwu"));
map.put("14", new User("4", "趙六"));
model.addAttribute("usersMap", map);
return "indexThymeleaf";
}
- 不使用狀態變量迭代循環
不使用狀態變量迭代循環users
中的對象,實例如下。
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="u : ${users}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
</tr>
</table>
- 使用狀態變量迭代循環
使用狀態變量迭代循環users
中的對象,實例如下。
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>index</th>
<th>count</th>
<th>size</th>
<th>even</th>
<th>odd</th>
<th>first</th>
<th>last</th>
</tr>
<tr th:each="u,var : ${users}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
<td th:text="${var.index}"></td>
<td th:text="${var.count}"></td>
<td th:text="${var.size}"></td>
<td th:text="${var.even}"></td>
<td th:text="${var.odd}"></td>
<td th:text="${var.first}"></td>
<td th:text="${var.last}"></td>
</tr>
</table>
狀態變量屬性:
index
:當前迭代器的索引 從 0 開始count
:當前迭代對象的計數 從 1 開始size
:被迭代對象的長度even/odd
:布爾值,當前循環是否是偶數/奇數 從 0 開始first
:布爾值,當前循環的是否是第一條,如果是返回 true 否則返回 falselast
:布爾值,當前循環的是否是最後一條,如果是則返回 true 否則返回 false
3. 迭代循環Map
迭代循環Map類型的對象。
<table border="1">
<tr>
<th>entrys</th>
</tr>
<tr th:each="entrys : ${usersMap}">
<td th:text="${entrys}"></td>
</tr>
</table>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>ID</th>
<th>Name</th>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="entrys : ${usersMap}">
<!-- 方式一 -->
<td th:each="entry:${entrys}" th:text="${entry.value.id}" />
<td th:each="entry:${entrys}" th:text="${entry.value.name}" />
<!-- <td th:each="entry:${entrys}" th:text="${entry.key}" /> -->
<!-- 方式二 -->
<td th:each="entry:${entrys}">
<span th:text="${entry.value.id}"></span>
</td>
<td th:each="entry:${entrys}">
<span th:text="${entry.value.name}"></span>
</td>
<!-- <td th:each="entry:${entrys}">
<span th:text="${entry.key}"></span>
</td> -->
<!-- 方式三 -->
<td th:text="${entrys.value.id}" />
<td th:text="${entrys.value.name}" />
<!-- <td th:text="${entrys.key}" /> -->
</tr>
</table>
六、日期格式化和字符串拼接轉義
通過使用時間工具類#dates
來對日期進行格式化
model.addAttribute("nowDate", new Date());
<div th:text="${#dates.format(nowDate,'yyy/MM/dd')}"></div>
通過運算符 +
字符串拼接
<div th:text="'當前時間:' + ${#dates.format(nowDate,'yyy/MM/dd')}"></div>
通過 th:utext
實現字符串轉義
<div th:utext="${html}"></div>