摘要
看完本文你將掌握如下知識點:
- Spring Boot(2.0.4)中使用thymeleaf(3.0.9)的常用語法
項目準(zhǔn)備
依賴
<!--spring對thymeleaf的支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
開啟spring boot對thymeleaf的支持
##thymeleaf
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
#關(guān)閉頁面緩存
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
也可以通過@Bean的方式開啟支持
@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
log.info("thymeleafViewResolver");
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setContentType("text/html");
viewResolver.setCache(false);
return viewResolver;
}
@Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
開啟html頁面對thymeleaf語法的支持
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
</html>
語法
各種表達式語法
1.${...} 變量表達式放吩,用于展示后臺傳遞過來的變量(request和session中的值)
<input type="text" name="modify" th:value="${modify}"/>
<input type="text" name="id" th:value="${dataObj.id}"/>
<textarea name="logParamData" id="logParamData" th:text="${dataObj.logParamData}"></textarea>
以下兩種方式效果一致
<span th:text="${dataObj.name}"></span>
<span>[[${dataObj.name}]]</span>
字符串拼接损离,可以使用加號蓖柔,也可以使用豎線挖滤,以下兩種方式效果一致
<input type="checkbox" name="accessTypes" th:value="${item.id}+'_'+${type.id}" checked="checked"> [[${type.name}]
<input type="checkbox" name="accessTypes" th:value="${|${item.id}_${type.id}|}" checked="checked"> [[${type.name}]
#dates與java.util.Date對象的方法對應(yīng)捣卤,格式化渔肩、日期組件抽取等等
<td th:text="${#dates.format(item.logTime, 'yyyy-MM-dd')}"></td>
<td>[[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]</td>
2.#{...} 國際化消息表達式捉蚤,用于展示message.properties等國際化資源文件中的內(nèi)容
<input type="checkbox" name="selectAll" id="selectAll" th:text="#{common.choose}"/>
消息中需要傳遞變量的情況揉稚,多個變量逗號分割
<strong th:text="#{common.page.summary(${_pageBean.pageCount},${_pageBean.total})}">
以下兩種方式效果一致
<td th:text="#{common.operate}"></td>
<td>[[#{common.operate}]]</td>
3.@{...} 鏈接url表達式厨相,用于封裝url领曼,如contextPath補全
<link th:href="@{/resource/css/netqin.css}" rel="stylesheet"/>
用兩個豎線來拼接帶表達式的字符串
<script type="text/javascript" th:src="@{|/resource/js/i18n/list.#{locale}.js|}"></script>
帶請求參數(shù)的url,多個用逗號分割
<a th:href="@{/auth/systemLogger/edit.do(id=${item.id},flag=${flag})}" th:text="#{common.edit}"></a>
4.js和css中用到表達式時使用雙中括號的方式
var modify = "[[${modify}]]";
if(modify != "add"){
$("#password").attr("placeholder","[[#{user.detail.changeNotice}]]");
}
5.*{...} 選擇變量表達式蛮穿,用于簡寫變量名稱庶骄,需要配合th:object一起使用
<div th:object="${user}">
<p>firstName: <span th:text="*{firstName}"></span></p>
<p>lastName: <span th:text="*{lastName}"></span></p>
</div>
相當(dāng)于
<div>
<p>firstName: <span th:text="${user.firstName}"></span></p>
<p>lastName: <span th:text="${user.lastName}"></span></p>
</div>
6.~{...} 代碼塊表達式,用于在html中復(fù)用相同的結(jié)構(gòu)
語法:~{templatename::fragmentname}
示例:
common/model.html践磅,th:fragment="header"指定代碼塊名稱
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<META http-equiv="Pragma" content="no-cache">
<META http-equiv="Cache-Control" content="no-cache">
<META http-equiv="Expire" content="0">
<link th:href="@{/resource/css/bootstrap.min.css}" rel="stylesheet" />
<link th:href="@{/resource/css/ace.min.css}" rel="stylesheet" />
<link rel="stylesheet" th:href="@{/resource/css/font-awesome.min.css}" />
<script th:src="@{/resource/js/jquery-1.11.0.min.js}"></script>
</head>
<body>
</body>
</html>
demo.html单刁,th:replace="common/model::header",模板名稱::代碼塊名稱
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<header th:replace="common/model::header"></header>
<body>
</body>
</html>
說明:代碼塊表達式需要配合th屬性(th:insert府适,th:replace羔飞,th:include)一起使用。
th:insert:將代碼塊片段整個插入到使用了th:insert的HTML標(biāo)簽中细溅,
th:replace:將代碼塊片段整個替換使用了th:replace的HTML標(biāo)簽中褥傍,
th:include:將代碼塊片段包含的內(nèi)容插入到使用了th:include的HTML標(biāo)簽中,
遍歷
簡單示例
<tr th:each="item:${results}">
<td>
<input type="checkbox" name="ids" th:value="${item.id}" class="noborder"/>
</td>
<td th:text="${item.id}"></td>
<td>
[[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]
</td>
<td th:text="${item.logDesc}"></td>
<td th:text="${item.logUser}"></td>
</tr>
帶遍歷狀態(tài)的示例
<tr th:each="item,status:${results}" th:class="${status.odd}? 'odd':'even'">
<td>
<input type="checkbox" name="ids" th:value="${item.id}" class="noborder"/>
</td>
<td th:text="${item.id}"></td>
<td>
[[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]
</td>
<td th:text="${item.logDesc}"></td>
<td th:text="${item.logUser}"></td>
</tr>
- 狀態(tài)說明
index:當(dāng)前遍歷索引喇聊,從0開始
count:當(dāng)前遍歷索引恍风,從1開始
size:總元素數(shù)量
current:每一次遍歷的iter變量
even/odd:當(dāng)前遍歷是even還是odd,布爾屬性
first:當(dāng)前遍歷是第一個,布爾屬性
last:當(dāng)前遍歷是最后一個朋贬,布爾屬性
遍歷時可以自定義變量
th:with:用于定義變量凯楔,多個使用逗號分割
<span th:each="type,status:${accessTypes}" th:with="shwoName=${item.id}+'_'+${item.name}">
[[${shwoName}]]
<span th:if="${not status.last}">,</span>
</span>
條件判斷
th:if
判斷為true時才會顯示div,authorities為Set類型锦募,所以判斷是否包含時可以使用#sets.contains()方法摆屯,測試時發(fā)現(xiàn)使用#arrays.contains()方法時也可以
<div th:if="${dataObj.reserved}">
<li th:each="item:${dataObj.authorities}">
<input type="checkbox" name="authorities" th:value="${item.id}"
th:if="${dataObj.authorities ==null or not #sets.contains(dataObj.authorities,item)}">
<input type="checkbox" name="authorities" th:value="${item.id}"
checked="checked" th:if="${dataObj.authorities !=null and #sets.contains(dataObj.authorities,item)}">
<span th:text="${item.showNameRole}"></span>
</li>
</div>
如果要判斷為false時才會顯示div,可以判斷值是否等于false糠亩,或者使用th:unless
<div th:if="${dataObj.reserved==false}">
<li th:each="item:${dataObj.authorities}">
<input type="checkbox" name="authorities" th:value="${item.id}"><span th:text="${item.showNameRole}"></span>
</li>
</div>
<div th:unless="${dataObj.reserved}">
<li th:each="item:${dataObj.authorities}">
<input type="checkbox" name="authorities" th:value="${item.id}"><span th:text="${item.showNameRole}"></span>
</li>
</div>
- th:if 以下情況運算為true
值不為null
值為boolean且為true
值為數(shù)字且非0
值為字符且非0
值是字符串且不是:“false”虐骑,“off”,“no”
值是object,但不為null
th:switch 和 th:case
bool匹配
<div th:switch="${dataObj.reserved}">
<p th:case="true">true</p>
<p th:case="false">false</p>
</div>
字符串匹配赎线,要加單引號
<div th:switch="${item.showNameRole}">
<p th:case="'admin'">administrator</p>
<p th:case="'manager'">manager</p>
</div>
<div th:switch="${item.showNameRole}">
<p th:case="'admin'">administrator</p>
<p th:case="'manager'">manager</p>
<p th:case="*">unknow</p>
</div>
- 說明:th:case="*" 表示沒有匹配成功時顯示的內(nèi)容
運算符
- 字符串連接
+ : ${item.id}+'_'+${type.id}
|xxxx| : |The name is ${name}|
- 算術(shù)運算
+ , - , * , / , % (二元運算符)
- :負(fù)號(一元運算符)
- 布爾操作
and :且,or :或 (二元運算符)
!,not :非(一元操作符)
- 關(guān)系操作符
> , < , >= , <= (gt , lt , ge , le)
== , != (eq, ne)
表達式工具對象
#dates 與java.util.Date對象的方法對應(yīng)廷没,格式化、日期組件抽取等等
#calendars 類似#dates垂寥,與java.util.Calendar對象對應(yīng)
#numbers 格式化數(shù)字對象的工具方法
#strings 與java.lang.String對應(yīng)的工具方法:contains颠黎、startsWith、prepending/appending等等
#objects 用于對象的工具方法
#bools 用于布爾運算的工具方法
#arrays 用于數(shù)組的工具方法
#lists 用于列表的工具方法
#sets 用于set的工具方法
#maps 用于map的工具方法
#aggregates 用于創(chuàng)建數(shù)組或集合的聚合的工具方法
#messages 用于在變量表達式內(nèi)部獲取外化消息的工具方法滞项,與#{…}語法獲取的方式相同
#ids 用于處理可能重復(fù)出現(xiàn)(例如狭归,作為遍歷的結(jié)果)的id屬性的工具方法
使用springsecurity權(quán)限標(biāo)簽的方法
添加依賴
<!--如果項目中使用到了springsecurity4, 則要加入下面的依賴來使用權(quán)限標(biāo)簽-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
開啟命名空間支持
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
</html>
使用方式與jsp標(biāo)簽類似:
<a th:href="@{/auth/systemLogger/edit.do}" class="btn btn-success btn-xs no-hover" th:text="#{common.create}" sec:authorize="hasRole('LOGGER_ADD')"></a>
<button class="btn btn-danger btn-xs" id="delete" th:text="#{common.delete}" sec:authorize="hasRole('LOGGER_DELETE')"></button>
調(diào)用spring管理的bean的方法
語法:${@beanName.methodName(param,...)}
說明:beanName就是注冊時的名稱
示例:
#httpSession就是javax.servlet.http.HttpSession對象
#httpServletRequest就是javax.servlet.http.HttpServletRequest對象
<span th:text="${@commonService.clearSessionMessage(#httpServletRequest)}" style="display: none"></span>