Thymeleaf是個XML/XHTML/HTML5模板引擎,可以用於Web與非Web應用。
Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板創建方式,因此也可以用作靜態建模。你可以使用它創建經過驗證的XML與HTML模板。相對於編寫邏輯或代碼,開發者只需將標簽屬性添加到模板中即可。接下來,這些標簽屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。Thymeleaf的可擴展性也非常棒。你可以使用它定義自己的模板屬性集合,這樣就可以計算自定義表達式並使用自定義邏輯。這意味着Thymeleaf還可以作為模板引擎框架。
Thymeleaf的模板還可以用作工作原型,Thymeleaf會在運行期替換掉靜態值。例如下面的html文件,當作為靜態文件時,product name顯示為Red Chair,當運行在容器中並提供product這個對象時,product name的值會自動替換為product.description對應的值。下面就簡單的講一講springboot整合thymeleaf模板。
1.引入依賴
在maven(pom.xml)中直接引入:
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-thymeleaf</artifactId> 4 </dependency>
也可以在創建項目時候勾選thymeleaf模板,這樣會自動生成。
2.配置視圖解析器
(1)默認
spring-boot很多配置都有默認配置,比如默認頁面映射路徑為
classpath:/templates/*.html
同樣靜態文件路徑為
classpath:/static/
(2)自定義
在application.properties(或者application.yml)中可以配置thymeleaf模板解析器屬性.就像使用springMVC的JSP解析器配置一樣
1 #thymeleaf start 2 spring.thymeleaf.mode=HTML5 3 spring.thymeleaf.encoding=UTF-8 4 spring.thymeleaf.content-type=text/html 5 #開發時關閉緩存,不然沒法看到實時頁面 6 spring.thymeleaf.cache=false 7 #thymeleaf end
具體可以配置的參數可以查看 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 這個類,上面的配置實際上就是注入到該類中的屬性值.
3.編寫demo來說明使用方法
(1)控制器
1 @Controller 2 public class HelloController(){ 3 @RequestMapping(value = "/") 4 public String index(){ 5 return "index"; 6 } 7 }
這樣會返回一個新的視圖頁面index.html,當然也可以使用下面的方法
@RequestConteoller public class HelloController(){ @RequestMapping(value = "/") public ModelAndView index(){ return new ModelAndView("index"); } }
這樣能直接返回整個index頁面。
(2)view
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org" > 3 <head> 4 <meta charset="UTF-8"/> 5 <title>Title</title> 6 </head> 7 <body> 8 <b th:text="hello,world!"><b/> 9 </body> 10 </html>
注意,在html標簽里一定要引入 xmlns:th="http://www.thymeleaf.org" ,這樣thymeleaf模板才會啟用。至於thymeleaf的具體使用方法,以后在講。
(3)測試
訪問 localhost:8080/ 這個地址,會直接跳轉到 index.html 頁面,並顯示如下
4.基礎語法
(1)引入標簽
首先要在html標簽里引入xmlns:th="http://www.thymeleaf.org"才能使用th:*這樣的語法。
(2)獲取變量值
通過在標簽內部,使用 ${} 來取值,對於javaBean的話,使用 變量名.屬性名 來獲取,跟EL表達式一樣
注意:只有寫在標簽內部才會生效,例如: th:text=“hello” 的意思是使用hello來代替p之前的內容,p里原來的值是為了給前端開發展示用的,這樣做容易實現前后端分離。
(3)引入URL
thymeleaf對於引入URL是采用@{...}來獲取的
例如: <a th:href="@{http://www.baidu.com}">絕對路徑</a> 是訪問絕對路徑下的URL, <a th:href="@{/}">相對路徑</a> 是訪問相對路徑下的URL。
<a th:href="@{css/bootstrap.min.css}"> 是引入默認的static下的css文件夾下的bootstrap文件,類似的標簽有: th:href 和 th:src
(4)字符串替換
例如使用: <span th:text="'Welcome to our application, ' + ${user.name} + '!'"></span> 或者
<span th:text="|Welcome to our application, ${user.name}!|"></span> 都可以實現替換
注意:|…|中只能包含變量表達式${…},不能包含其他常量、條件表達式等。
(5)運算符
在表達式中可以使用各類算術運算符,例如 +, -, *, /, % .例如: th:with="isEven=(${prodStat.count} % 2 == 0)"
邏輯運算符 >, <, <=,>=,==,!= 都可以使用,唯一需要注意的是使用 <,> 時需要用它的HTML轉義符:
th:if="${prodStat.count} > 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
(6)條件
if/unless th:if是該標簽在滿足條件的時候才會顯示,unless是不成立時候才顯示,例如
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
Switch thymeleaf支付switch結構,默認屬性(default)用*表示,例如:
1 <div th:switch="${user.role}"> 2 <p th:case="'admin'">User is an administrator</p> 3 <p th:case="#{roles.manager}">User is a manager</p> 4 <p th:case="*">User is some other thing</p> 5 </div>
(7)循環
th:each是對於結果可以進行遍歷的數據集,例如:
1 <tr th:each="prod : ${prods}"> 2 <td th:text="${prod.name}">Onions</td> 3 <td th:text="${prod.price}">2.41</td> 4 <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> 5 </tr>
(8)Utilities
為了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),可以通過#直接訪問:
#dates
#calendars
#numbers
#strings
arrays
lists
sets
maps
…
例如:
${#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')}
${#dates.createNow()}
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
${#strings.startsWith(name,'Don')}
${#strings.endsWith(name,endingFragment)}
${#strings.length(str)}
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}
${#strings.randomAlphanumeric(count)}
(8)補充
在spring-boot1.4之后,支持thymeleaf3,可以更改版本號來進行修改支持.
3相比2極大的提高了效率,並且不需要標簽閉合,類似的link,img等都有了很好的支持,按照如下配置即可
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- set thymeleaf version --> <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> <!--set java version--> <java.version>1.8</java.version> </properties>
(9)一些常用標簽的使用說明
th:text 替換原來text中的東西
th:value 替換原來value的值
th:object 替換標簽的對象,th:object=“對象”
th:field 填充,如圖上面又對象,可以直接用*{屬性}取值
th:checked 當check的值為true時候為選中,false時為未選中
th:remove 刪除
th:href 用@{}替換連接地址
th:if 如果值為true的時候才顯示標簽,否則不顯示
th:unless 不成立的時候才顯示
th:each 用戶循環遍歷結果集
th:style 替換樣式
th:action 替換action地址,用@{}取地址
th:alt 用@{}取地址
th:class 替換class的樣式
th:fragment 定義一個framemet模板,在后面引用他
(10)實例一:頁面的引用與替換
日常開發中,我們經常會講導航,頁尾,菜單單獨提取成模板供其他頁面使用,在thymeleaf,我們可以使用th:fragment屬性來定義一個模板,例如:
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org" 3 xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"> 4 <head> 5 <meta charset="utf-8"/> 6 </head> 7 <body> 8 <div class="container-fluid all"> 9 <div class="sidebar"> 10 <ul class="nav"> 11 <li><a th:href="@{/index}"> 首頁</a></li> 12 <li><a th:href="@{/add}"> 增加用戶</a></li> 13 <li><a th:href="@{#}"> 員工信息</a></li> 14 <li><a th:href="@{#}"> 工資信息</a></li> 15 <li><a th:href="@{#}"> 任務信息</a></li> 16 <li><a th:href="@{#}"> 人員調動</a></li> 17 <li><a th:href="@{#}"> 檔案管理</a></li> 18 <li><a th:href="@{#}"> 歷史記錄</a></li> 19 </ul> 20 </div> 21 <div class="maincontent row"> 22 23 <div th:fragment="content"> 24 </div> 25 26 </div> 27 </div> 28 <a href="#top" id="goTop"><i class="fa fa-angle-up fa-3x"></i></a> 29 </body> 30 </html>
1.上面定義了一個叫做content的片段,我們可以使用 th:include 或者 th:replace 屬性來使用他,例如我們可以新建一個簡單的頁尾模板,
新建一個html文件,路徑如下:/WEB-INF/templates/footer.html ,然后我們可以在footer.html文件中引入上面的content片段。
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"/> 5 <title>Title</title> 6 </head> 7 <body> 8 <div th:include="footer :: content"></div> 9 </body> 10 </html>
其中 th:include 中的參數格式為 templatename::[domselector] ,其中templatename是模板名(如footer),domselector是可選的dom選擇器。如果只寫templatename,不寫domselector,則會加載整個模板。我們也可以使用三目表達式來寫,例如 :
<div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>
模板片段可以被包含在任意th:*屬性中,並且可以使用目標頁面中的上下文變量。
2.不通過th:fragment引用模板,我們可以通過強大的dom選擇器,在不添加任何fragment屬性的情況定義模板,例如:
1 <div id="copy-section"> 2 © xxxxxx 3 </div>
通過dom選擇器來加載模板,如id為copy-section, <div th:include="footer :: #copy-section">
3.使用layout布局加載模板
在html標簽中引用 xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" ,使用layout來進行布局,然后在需要被引用的head頁面,要修改的地方添加
<div layout:fragment="content"></div> 片段,例如:
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org" 3 xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"> 4 <head> 5 <meta charset="utf-8"/> 6 </head> 7 <body> 8 <div class="container-fluid all"> 9 <div class="sidebar"> 10 <ul class="nav"> 11 <li><a th:href="@{/index}"> 首頁</a></li> 12 <li><a th:href="@{/add}"> 增加用戶</a></li> 13 <li><a th:href="@{#}"> 員工信息</a></li> 14 <li><a th:href="@{#}"> 工資信息</a></li> 15 <li><a th:href="@{#}"> 任務信息</a></li> 16 <li><a th:href="@{#}"> 人員調動</a></li> 17 <li><a th:href="@{#}"> 檔案管理</a></li> 18 <li><a th:href="@{#}"> 歷史記錄</a></li> 19 </ul> 20 </div> 21 <div class="maincontent row"> 22 23 <div th:fragment="content"> 24 </div> 25 26 </div> 27 </div> 28 <a href="#top" id="goTop"><i class="fa fa-angle-up fa-3x"></i></a> 29 </body> 30 </html>
然后新建一個html文件,在html中引入 layout:decorator="head" ,然后直接在body里添加 <div layout:fragment="content"></div> ,在新的頁面中的div里添加需要的內容,加載出來就是整合了head.html的新頁面。例如:
1 <!DOCTYPE html> 2 <html xmlns:th="http://www.thymeleaf.org" 3 xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" 4 layout:decorator="head"> 5 <head> 6 <meta charset="UTF-8"/> 7 <title>添加用戶</title> 8 </head> 9 <body> 10 11 <div layout:fragment="content" class="col-sm-12"> 12 </div> 13 14 </body> 15 </html>
在div里添加內容,加載出來的頁面會包括head的內容,而新頁面div的內容,會顯示在head頁面中的 <div th:fragment="content"></div> 中,這樣使用布局更方便。
4.th:include與th:replace的區別
th:include 是加載模板的內容,而 th:replace 則會替換當前標簽為模板中的標簽,例如:
1 <body> 2 <div th:include="footer :: copy"></div> 3 <div th:replace="footer :: copy"></div> 4 </body>
這樣顯示的結果為:
1 <body> 2 <div> © 2016 </div> 3 <footer>© 2016 </footer> 4 </body>
第一個是加載了模板標簽內的內容,第二個是替換了整個標簽。
參考:http://blog.csdn.net/u012706811/article/details/52185345
http://blog.csdn.net/pdw2009/article/details/44700897
https://www.jianshu.com/p/ed9d47f92e37