SpringBoot引入Thymeleaf
1.Thymeleaf簡介
Thymeleaf是個XML/XHTML/HTML5模板引擎,可以用於Web與非Web應用
Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板建立方式,因此也可以用作靜態建模,Thymeleaf的可擴充套件性也非常棒。你可以使用它定義自己的模板屬性集合,這樣就可以計算自定義表示式並使用自定義邏輯,Thymeleaf還可以作為模板引擎框架。
2.引入Thymeleaf
- 引入依賴
在maven(pom.xml)中直接引入:
<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>
- 配置Thymeleaf
在application.yml配置Thymeleaf
server: port: 8000 spring: thymeleaf: cache: false # 關閉頁面快取 encoding: UTF-8 # 模板編碼 prefix: classpath:/templates/# 頁面對映路徑 suffix: .html # 試圖後的字尾 mode: HTML5 # 模板模式 # 其他具體配置可參考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties # 上面的配置實際上就是注入該類的屬性值
- demo示例
建立IndexController
@Controller public class IndexController { // 返回檢視頁面 @RequestMapping("index") public String index(){ return "index"; } }
建立index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello Thymeleaf! </body> </html>
建立TestController
@RestController public class TestController { // 返回整個頁面 @RequestMapping("/test") public ModelAndView test(){ return new ModelAndView("test"); } }
建立test.html
<!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)"
邏輯運算子 (>, <, <=,>=,==,!=)
需要注意的是使用<,>的時候需要轉義
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...