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)中直接引入:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
也可以在創建項目時候勾選thymeleaf模板,這樣會自動生成。
2.配置視圖解析器
(1)默認
spring-boot很多配置都有默認配置,比如默認頁面映射路徑為
classpath:/templates/*.html
同樣靜態文件路徑為
classpath:/static/
(2)自定義
在application.properties(或者application.yml)中可以配置thymeleaf模板解析器屬性.就像使用springMVC的JSP解析器配置一樣
#thymeleaf startspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html #開發時關閉緩存,不然沒法看到實時頁面spring.thymeleaf.cache=false#thymeleaf end
具體可以配置的參數可以查看 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 這個類,上面的配置實際上就是注入到該類中的屬性值.
3.編寫demo來說明使用方法
(1)控制器
@Controllerpublic class HelloController(){@RequestMapping(value = "/")public String index(){return "index";}}
這樣會返回一個新的視圖頁面index.html,當然也可以使用下面的方法
@RequestConteollerpublic class HelloController(){@RequestMapping(value = "/")public ModelAndView index(){return new ModelAndView("index");}}
這樣能直接返回整個index頁面。
(2)view
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body><b th:text="hello,world!"><b/>
</body>
</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是采用@{…}來獲取的
例如: 絕對路徑 是訪問絕對路徑下的URL, 相對路徑 是訪問相對路徑下的URL。
是引入默認的static下的css文件夾下的bootstrap文件,類似的標簽有: th:href 和 th:src
(4)字符串替換
例如使用: 或者
<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)用*表示,例如:
<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>
(7)循環
th:each是對于結果可以進行遍歷的數據集,例如:
<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>
(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屬性來定義一個模板,例如:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head><meta charset="utf-8"/>
</head>
<body>
<div class="container-fluid all"><div class="sidebar"><ul class="nav"><li><a th:href="@{/index}"> 首頁</a></li><li><a th:href="@{/add}"> 增加用戶</a></li><li><a th:href="@{#}"> 員工信息</a></li><li><a th:href="@{#}"> 工資信息</a></li><li><a th:href="@{#}"> 任務信息</a></li><li><a th:href="@{#}"> 人員調動</a></li><li><a th:href="@{#}"> 檔案管理</a></li><li><a th:href="@{#}"> 歷史記錄</a></li></ul></div><div class="maincontent row"><div th:fragment="content"></div></div>
</div>
<a href="#top" id="goTop"><i class="fa fa-angle-up fa-3x"></i></a>
</body>
</html>
1.上面定義了一個叫做content的片段,我們可以使用 th:include 或者 th:replace 屬性來使用他,例如我們可以新建一個簡單的頁尾模板,
新建一個html文件,路徑如下:/WEB-INF/templates/footer.html ,然后我們可以在footer.html文件中引入上面的content片段。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"/><title>Title</title>
</head>
<body><div th:include="footer :: content"></div>
</body>
</html>
其中 th:include 中的參數格式為 templatename::[domselector] ,其中templatename是模板名(如footer),domselector是可選的dom選擇器。如果只寫templatename,不寫domselector,則會加載整個模板。我們也可以使用三目表達式來寫,例如 :
模板片段可以被包含在任意th:*屬性中,并且可以使用目標頁面中的上下文變量。
2.不通過th:fragment引用模板,我們可以通過強大的dom選擇器,在不添加任何fragment屬性的情況定義模板,例如:
<div id="copy-section">© xxxxxx</div>
通過dom選擇器來加載模板,如id為copy-section,
3.使用layout布局加載模板
在html標簽中引用 xmlns:layout=“http://www.ultraq.net.nz/web/thymeleaf/layout” ,使用layout來進行布局,然后在需要被引用的head頁面,要修改的地方添加
片段,例如:<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"><head><meta charset="utf-8"/></head><body><div class="container-fluid all"><div class="sidebar"><ul class="nav"><li><a th:href="@{/index}"> 首頁</a></li><li><a th:href="@{/add}"> 增加用戶</a></li><li><a th:href="@{#}"> 員工信息</a></li><li><a th:href="@{#}"> 工資信息</a></li><li><a th:href="@{#}"> 任務信息</a></li><li><a th:href="@{#}"> 人員調動</a></li><li><a th:href="@{#}"> 檔案管理</a></li><li><a th:href="@{#}"> 歷史記錄</a></li></ul></div><div class="maincontent row"><div th:fragment="content"></div></div></div><a href="#top" id="goTop"><i class="fa fa-angle-up fa-3x"></i></a></body></html>
然后新建一個html文件,在html中引入 layout:decorator=“head” ,然后直接在body里添加
,在新的頁面中的div里添加需要的內容,加載出來就是整合了head.html的新頁面。例如:<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"layout:decorator="head">
<head><meta charset="UTF-8"/><title>添加用戶</title>
</head>
<body><div layout:fragment="content" class="col-sm-12">
</div></body>
</html>
在div里添加內容,加載出來的頁面會包括head的內容,而新頁面div的內容,會顯示在head頁面中的
中,這樣使用布局更方便。4.th:include與th:replace的區別
th:include 是加載模板的內容,而 th:replace 則會替換當前標簽為模板中的標簽,例如:
<body> <div th:include="footer :: copy"></div><div th:replace="footer :: copy"></div>
</body>
這樣顯示的結果為:
<body> <div> © 2016 </div> <footer>© 2016 </footer> </body>
第一個是加載了模板標簽內的內容,第二個是替換了整個標簽。