1.Thymeleaf簡介
Thymeleaf是個XML/XHTML/HTML5模板引擎,能夠用於Web與非Web應用
Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板建立方式,所以也能夠用做靜態建模,Thymeleaf的可擴展性也很是棒。你能夠使用它定義本身的模板屬性集合,這樣就能夠計算自定義表達式並使用自定義邏輯,Thymeleaf還能夠做爲模板引擎框架。
2.引入Thymeleafcss
在maven(pom.xml)中直接引入:html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在application.yml配置Thymeleafgit
server: port: 8000 spring: thymeleaf: cache: false # 關閉頁面緩存 encoding: UTF-8 # 模板編碼 prefix: classpath:/templates/ # 頁面映射路徑 suffix: .html # 試圖後的後綴 mode: HTML5 # 模板模式 # 其餘具體配置可參考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties # 上面的配置實際上就是注入該類的屬性值
建立IndexControllergithub
@Controller public class IndexController { // 返回視圖頁面 @RequestMapping("index") public String index(){ return "index"; } }
建立index.htmlweb
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello Thymeleaf! </body> </html>
建立TestControllerspring
@RestController public class TestController { // 返回整個頁面 @RequestMapping("/test") public ModelAndView test(){ return new ModelAndView("test"); } }
建立test.htmlbootstrap
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello Thymeleaf! </br> By: ModelAndView </body> </html>
3.測試結果
4.Thymeleaf基礎語法及使用
1.引入標籤
html標籤裏引入xmlns:th="http://www.thymeleaf.org"才能使用th:*這樣的語法
2.引入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
3.獲取變量
經過${}取值,對於JavaBean的話,使用變量名.屬性名獲取
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=(${stat.number} % 1 == 0)"
邏輯運算符 (>, <, <=,>=,==,!=)
須要注意的是使用<,>的時候須要轉義app
th:if="${stat.number} > 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
6.條件
if/unless th:if是該標籤在知足條件的時候纔會顯示,unless是不成立時候才顯示
<a th:href="@{/login}" th:unless=${user.number != 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.循環
<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
內置在Context中,能夠直接經過#訪問 #dates #calendars #numbers #strings arrays lists sets maps …
5.小結
本文講述瞭如何在Spring Boot中引入模板引擎Thymeleaf以及Thymeleaf基礎語法和實際使用
本文GitHub地址:https://github.com/ishuibo/Sp...