本文首發於: https://y0ngb1n.github.io/a/5...
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties>
主要增長 spring-boot-starter-thymeleaf
依賴:css
spring-boot-starter-thymeleaf
:自動裝配 Thymeleaf 模板引擎<dependencies> ... <!-- Thymeleaf Start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Thymeleaf End --> ... </dependencies>
application.yml
html
spring: thymeleaf: cache: false # 是否開啓模板緩存,默認爲:true,開發時關閉緩存,否則無法看到實時頁面! mode: HTML # 指定模板的模式,默認爲:HTML encoding: UTF-8 # 指定模板的編碼,默認爲:UTF-8 prefix: classpath:/templates/ # 指定模板的前綴,默認爲:classpath:/templates/ suffix: .html # 指定模板的後綴,默認爲:.html servlet: content-type: text/html # 指定 Content-Type 值,默認爲:text/html
從 org.thymeleaf.templatemode.TemplateMode
中可見 Thymeleaf
從 3.0.0
版本開始使用 HTML
替代 HTML五、LEGACYHTML五、XHTML、VALIDXHTML
。若是還在使用 3.0.0
之前的版本,想要使用非嚴格的 HTML,須要作如下配置:前端
pom.xml
中引入 nekohtml
依賴application.yml
中配置 spring.thymeleaf.mode=LEGACYHTML5
更多屬性配置請參考「Appendix A. Common application properties」中 # THYMELEAF (ThymeleafAutoConfiguration)
模塊的屬性介紹。(TIPS:使用 CTRL + F
進行快速定位)java
建立一個 Controller,爲 message
屬性賦值並設置跳轉,代碼以下:git
IndexController.java
github
@Controller public class IndexController { @GetMapping(path = {"/", "index"}) public String indexPage(Model model) { model.addAttribute("message", "Hello Thymeleaf!"); return "index"; } }
在 templates
目錄下建立 index.html
文件,並在 html
標籤中聲明 Thymeleaf 命名空間 xmlns:th="http://www.thymeleaf.org"
,代碼以下:spring
index.html
segmentfault
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Thymeleaf</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html>
其中關鍵的代碼是:後端
xmlns:th="http://www.thymeleaf.org"
主要是讓 IDE 識別 Thymeleaf 命名空間,這樣在標籤裏輸入 th:
後,IDE 會提示相應的語法,方便開發!不加入這句代碼也不會影響 Thymeleaf 模板引擎的渲染,以及頁面的正常顯示。瀏覽器
啓動成功後,訪問 http://127.0.0.1:8080,便可看到效果:
訪問結果:Hello Thymeleaf!
templates
目錄<p th:text="'Hello! ' + ${name} + '!'" >name</p>
能夠看出獲取變量值用 $
符號,對於 JavaBean 的話使用 變量名.屬性名
方式獲取,這點和 EL
表達式同樣。
另外 $
表達式只能寫在 th
標籤內部,否則不會生效,上面例子就是使用 th:text
標籤的值替換 <p>...</p>
標籤裏面的值,至於 p
裏面的原有的值只是爲了給前端開發時作展現用的。這樣的話很好的作到了先後端分離。
th:text
與 th:utext
th:text
:以純文本的方式輸出th:utext
:以 HTML 標籤的方式輸出,瀏覽器能正常渲染HTML 代碼:
<body> <h2 th:text="' th:text   » ' + ${content}">以純文本的方式輸出</h2> <h2 th:utext="'th:utext » ' + ${content}">以 HTML 標籤的方式輸出,瀏覽器能正常渲染</h2> </body>
JAVA 代碼:
@GetMapping("/text-utext") public String textAndutext(Model model) { model.addAttribute("content", "<span style='color:red'>thymeleaf text output</span>"); return "text-utext"; }
對於 URL 的處理是經過語法 @{…}
來處理的:
HTML 代碼:
<body> <ul> <li> <a th:href="@{https://github.com/{username}(username=${username})}">絕對路徑 1</a>, <a th:href="@{https://www.baidu.com}">絕對路徑 2</a> </li> <li> <a th:href="@{/}">相對路徑</a> </li> <li> <a th:href="@{/css/app.css}">Content 路徑,默認訪問 static 下的 CSS 文件</a> </li> </ul> </body>
JAVA 代碼:
@GetMapping("/refer-url") public String referUrl(Model model) { model.addAttribute("username", "y0ngb1n"); return "refer-url"; }
相似的標籤有:th:href
和 th:src
不少時候可能咱們只須要對一大段文字中的某一處地方進行替換,能夠經過字符串拼接操做完成:
<p th:text="'Welcome to our application, ' + ${user.name} + '!'">
能夠用另外一種更簡潔的方式:
<p th:text="|Welcome to our application, ${user.name}!|">
文字替換自己能夠和與其餘表達式聯合使用:
<p th:text="${onevar} + ', ' + |${twovar}, ${threevar}|">
固然這種形式限制比較多,|…|
中只能包含變量表達式 ${…}
,不能包含其餘常量、條件表達式等。
HTML 代碼:
<body> <p th:text="'Welcome to our application, ' + ${user.name} + '!'"> <p th:text="|Welcome to our application, ${user.name}!|"> <p th:text="${onevar} + ', ' + |${twovar}, ${threevar}|"> </body>
JAVA 代碼:
@GetMapping("replace-text") public String replaceText(Model model) { model.addAttribute("user", user); model.addAttribute("onevar", "one"); model.addAttribute("twovar", "two"); model.addAttribute("threevar", "three"); return "replace-text"; }
在表達式中可使用各種算術運算符,例如 +, -, *, /, %
:
th:with="isEven=(${user.age} % 2 == 0)"
邏輯運算符 >, <, <=, >=, ==, !=
均可以使用,惟一須要注意的是使用 <, >
時須要用它的 HTML 轉義符:
th:if="${user.age} > 1" th:text="'Environment is ' + ((${env} == 'dev') ? 'Development' : 'Production')"
HTML 代碼:
<body> <h2 th:text="|name: ${user.name}, age: ${user.age}, env: ${env}|"></h2> <p th:with="isEven=(${user.age} % 2 == 0)">年齡爲偶數</p> <p th:with="isEven=(${user.age == 18})">喲,才 18 吶!</p> <p th:if="${user.age} > 18">當前年齡大於 18</p> <div th:class="${env} == 'dev' ? 'dev' : 'prod'"></div> <p th:text="'當前環境:' + ((${env} == 'dev') ? 'Development' : 'Production')"></p> </body>
JAVA 代碼:
@GetMapping("/operator") public String operator(Model model) { model.addAttribute("user", user); model.addAttribute("env", "dev"); return "operator"; }
th:if, th:unless
使用 th:if
和 th:unless
屬性進行條件判斷,下面的例子中,標籤只有在 th:if
中條件成立時才顯示:
<a th:href="@{/login}" th:if=${user == null}>Login</a> <a th:href="@{/login}" th:unless=${user != null}>Login</a>
th:unless
於 th:if
剛好相反,只有表達式中的條件不成立,纔會顯示其內容。
th:switch, th:case
支持多路選擇 Switch 結構:
<div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> </div>
默認屬性 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>
消息表達式:
#{...}
,也稱爲文本外部化、國際化或 i18n
HTML 代碼:
<body> <a th:href="@{/login}" th:unless="${user == null}">登陸</a> <p th:if="${user != null}">歡迎,<span th:text="|${user.name}(role: ${user.role})|">tony</span></p> <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> </body>
JAVA 代碼:
@GetMapping("/condition") public String condition(Model model) { model.addAttribute("user", user); return "condition"; }
渲染列表數據是一種很是常見的場景,例如如今有 n 條記錄須要渲染成一個表格,該數據集合必須是能夠遍歷的,使用 th:each
標籤:
HTML 代碼:
<body> <table> <tr> <th>NAME</th> <th>AGE</th> <th>ADMIN</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.name}">Onions</td> <td th:text="${user.age}">22</td> <td th:text="${user.role} == 'admin' ? #{true} : #{false}">yes</td> </tr> </table> </body>
能夠看到,須要在被循環渲染的元素(這裏是)中加入 th:each
標籤,其中 th:each="prod : ${prods}"
意味着對集合變量 prods
進行遍歷,循環變量是 prod
在循環體中能夠經過表達式訪問。
JAVA 代碼:
@GetMapping("/loop") public String loop(Model model) { List<User> users = new ArrayList<>(3); users.add(user); users.add(User.builder().name("tony").age(23).role("user").build()); users.add(User.builder().name("tom").age(21).role("user").build()); model.addAttribute("users", users); return "loop"; }
更多標籤用法請參考「 Thymeleaf 經常使用語法」、「 Thymeleaf 參考手冊」解鎖更多技巧 🤪