學習完整課程請移步 互聯(lián)網(wǎng) Java 全棧工程師
引入 Thymeleaf
修改 html 標簽用于引入 thymeleaf 引擎,這樣才可以在其他標簽里使用 th:*
語法剂娄,這是下面語法的前提。
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
獲取變量值
<p th:text="'Hello韵吨!, ' + ${name} + '!'" >name</p>
可以看出獲取變量值用 $
符號,對于javaBean的話使用 變量名.屬性名
方式獲取,這點和 EL
表達式一樣.
另外 $
表達式只能寫在th標簽內(nèi)部,不然不會生效,上面例子就是使用 th:text
標簽的值替換 p
標簽里面的值,至于 p
里面的原有的值只是為了給前端開發(fā)時做展示用的.這樣的話很好的做到了前后端分離.
引入 URL
Thymeleaf 對于 URL 的處理是通過語法 @{…}
來處理的
<a th:href="@{http://www.baidu.com}">絕對路徑</a>
<a th:href="@{/}">相對路徑</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,默認訪問static下的css文件夾</a>
類似的標簽有:th:href
和 th:src
字符串替換
很多時候可能我們只需要對一大段文字中的某一處地方進行替換座掘,可以通過字符串拼接操作完成:
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
一種更簡潔的方式是:
<span th:text="|Welcome to our application, ${user.name}!|">
當然這種形式限制比較多苞尝,|…|中只能包含變量表達式${…}说铃,不能包含其他常量杨赤、條件表達式等。
運算符
在表達式中可以使用各類算術運算符截汪,例如+, -, *, /, %
th:with="isEven=(${prodStat.count} % 2 == 0)"
邏輯運算符>, <, <=,>=,==,!=都可以使用植捎,唯一需要注意的是使用<,>時需要用它的HTML轉義符:
th:if="${prodStat.count} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
條件
if/unless
Thymeleaf 中使用 th:if
和 th:unless
屬性進行條件判斷衙解,下面的例子中,標簽只有在 th:if
中條件成立時才顯示:
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:unless
于 th:if
恰好相反焰枢,只有表達式中的條件不成立蚓峦,才會顯示其內(nèi)容舌剂。
switch
Thymeleaf 同樣支持多路選擇 Switch 結構:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
默認屬性 default 可以用 * 表示:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
循環(huán)
渲染列表數(shù)據(jù)是一種非常常見的場景,例如現(xiàn)在有 n 條記錄需要渲染成一個表格暑椰,該數(shù)據(jù)集合必須是可以遍歷的霍转,使用 th:each
標簽:
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p>
</body>
可以看到,需要在被循環(huán)渲染的元素(這里是)中加入 th:each
標簽一汽,其中 th:each="prod : ${prods}"
意味著對集合變量 prods
進行遍歷避消,循環(huán)變量是 prod
在循環(huán)體中可以通過表達式訪問。