本文在我的技術博客【鳥不拉屎】同步發佈,詳情可猛戳 亦可掃描文章末尾二維碼關注我的公衆號【鳥不拉屎】javascript
通常來講,經常使用的模板引擎有JSP、Velocity、Freemarker、Thymeleaf 。css
SpringBoot推薦的 Thymeleaf – 語法更簡單,功能更強大;html
Thymeleaf是一種Java XML/XHTML/HTML5模板引擎,能夠在Web和非Web環境中使用。 它更適合在基於MVC的Web應用程序的視圖層提供XHTML/HTML5,但即便在脫機環境中,它也能夠處理任何XML文件。它提供了完整的Spring Framework集成。java
它們分爲四類:git
變量表達式即 OGNL 表達式或 Spring EL 表達式(在 Spring 術語中也叫 model attributes)。以下所示: ${session.user.name}
github
它們將以HTML標籤的一個屬性來表示:web
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
複製代碼
選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執行,以下: *{customer.name}
spring
被指定的 object 由 th:object 屬性定義:數組
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
複製代碼
文字國際化表達式容許咱們從一個外部文件獲取區域文字信息(.properties),用 Key 索引 Value,還能夠提供一組參數(可選).緩存
#{main.title}
#{message.entrycreated(${entryId})}
複製代碼
能夠在模板文件中找到這樣的表達式代碼:
<table>
...
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
...
</table>
複製代碼
URL 表達式指的是把一個有用的上下文或回話信息添加到 URL,這個過程常常被叫作 URL 重寫。 @{/order/list}
URL還能夠設置參數: @{/order/details(id=${orderId})}
相對路徑: @{../documents/report}
讓咱們看這些表達式:
<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">
複製代碼
若是不考慮上下文的狀況下,二者沒有區別;星號語法評估在選定對象上表達,而不是整個上下文 什麼是選定對象?就是父標籤的值,以下:
<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>
複製代碼
'one text', 'Another one!',…
0, 34, 3.0, 12.3,…
true, false
null
one, sometext, main,…
+
|The name is ${name}|
+, -, *, /, %
-
and, or
!, not
>, <, >=, <= (gt, lt, ge, le)
==, != (eq, ne)
(if) ? (then)
(if) ? (then) : (else)
(defaultvalue)
全部這些特徵能夠被組合並嵌套:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
複製代碼
官方文檔詳細的一批: www.thymeleaf.org/doc/tutoria…
關鍵字 | 功能介紹 | 案例 |
---|---|---|
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="src=@{/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。
簡單表達式
數據的類型
文本操做
算術運算
布爾運算
條件運算符
條件判斷
表達式裏面的對象能夠幫助咱們處理要展現的內容,好比表達式的工具類dates能夠格式化時間,這些內置類的熟練使用,可讓咱們使用Thymeleaf的效率提升不少。
表達式實用工具類:
<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}!|">
複製代碼
Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>
標籤只有在th:if
中條件成立時才顯示:
<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>
複製代碼
th:unless
於 th:if
剛好相反,只有表達式中的條件不成立,纔會顯示其內容。
也可使用 (if) ? (then) : (else)
這種語法來判斷顯示的內容
<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稱做狀態變量,屬性有:
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>
複製代碼
幾點說明:
(orderId=${o.id})
表示將括號內的內容做爲 URL 參數處理,該語法避免使用字符串拼接,大大提升了可讀性@{...}
表達式中能夠經過{orderId}
訪問 Context 中的 orderId 變量@{/order}
是 Context 相關的相對路徑,在渲染時會自動添加上當前 Web 應用的 Context 名字,假設 context 名字爲 app,那麼結果應該是 /app/order
內聯文本:[[…]] 內聯文本的表示方式,使用時,必須先用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';
/* -]*/
複製代碼
爲了模板更加易用,Thymeleaf 還提供了一系列 Utility 對象(內置於 Context 中),能夠經過 # 直接訪問:
下面用一段代碼來舉例一些經常使用的方法:
/*
* 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()}
複製代碼
/*
* 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)}
複製代碼
我認爲能夠大體分爲四步:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
複製代碼
server:
port: 8081
spring:
thymeleaf:
# 是否啓用
enabled: true
# 模板編碼
encoding: UTF-8
# 模板模式
mode: HTML5
# 模板存放路徑
prefix: classpath:/templates/
# 模板後綴
suffix: .html
# 啓用緩存,建議生產開啓
cache: false
# 校驗模板是否存在
check-template-location: true
# Content-type值
servlet:
content-type: text/html
# 加配置靜態資源
resources:
static-locations: classpath:/
複製代碼
@RequestMapping("/me")
public String kownMe(Map<String,Object> map) {
List<String> list = new ArrayList<String>();
list.add("鳥不拉屎:一個正在努力Coding的將來架構師");
list.add("記錄菜鳥的成長");
list.add("我的博客:https://niaobulashi.com");
list.add("github博客:https://niaobulashi.github.io");
map.put("msg", "Yoyoyoyoyo");
map.put("images", "Yoyoyoyoyo");
map.put("lists", list);
return "me";
}
複製代碼
注意:返回的」me″是我HTML文件 me.html的名稱哦
只要把寫好的HTML頁面放在 classpath:/templates/ 下,thymeleaf就能自動渲染。
注意導入:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
複製代碼
不然沒提示哦~
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<meta content="text/html;charset=UTF-8"/>
<title>鳥不拉屎</title>
<link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<body>
<div class="layui-container">
<h1>templates示例</h1>
<!-- th:text="" 將h2的文本值視爲指定參數 -->
<hr>
<h2 th:text="${msg}">這是h2</h2>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>循環</legend>
</fieldset>
<table style="text-align: center" class="layui-table" lay-skin="line" >
<colgroup>
<col width="350">
</colgroup>
<thead>
<tr>
<th>NAME</th>
</tr>
</thead>
<tbody>
<!-- th循環遍歷傳來的參數 -->
<tr th:each="str : ${lists}" >
<th th:text="${str}" ></th>
</tr>
</tbody>
</table>
<img th:src="${images}" >
</div>
</body>
</html>
複製代碼
運行效果(樣式用的layUI~~):