Spring Boot 2.0 整合 Thymeleaf 模塊引擎

開發環境

<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 依賴:

  • spring-boot-starter-thymeleaf:自動裝配 Thymeleaf 模板引擎
<dependencies>
  ...

  <!-- Thymeleaf Start -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <!-- Thymeleaf End -->
  
  ...
</dependencies>

配置 Thymeleaf

application.yml

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 中可見 Thymeleaf3.0.0 版本開始使用 HTML 替代 HTML5、LEGACYHTML5、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 進行快速定位)

創建測試 Controller

創建一個 Controller,爲 message 屬性賦值並設置跳轉,代碼如下:

IndexController.java

@Controller
public class IndexController {

  @GetMapping(path = {"/", "index"})
  public String indexPage(Model model) {
    model.addAttribute("message", "Hello Thymeleaf!");
    return "index";
  }
}

創建測試 HTML 頁面

templates 目錄下創建 index.html 文件,並在 html 標籤中聲明 Thymeleaf 命名空間 xmlns:th="http://www.thymeleaf.org",代碼如下:

index.html

<!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

訪問結果:Hello Thymeleaf!


Thymeleaf 常用語法

獲取變量值

<p th:text="'Hello! ' + ${name} + '!'" >name</p>

可以看出獲取變量值用 $ 符號,對於 JavaBean 的話使用 變量名.屬性名 方式獲取,這點和 EL 表達式一樣。

另外 $ 表達式只能寫在 th 標籤內部,不然不會生效,上面例子就是使用 th:text 標籤的值替換 <p>...</p> 標籤裏面的值,至於 p 裏面的原有的值只是爲了給前端開發時做展示用的。這樣的話很好的做到了前後端分離。

內容信息輸出:th:textth:utext

  • th:text:以純文本的方式輸出
  • th:utext:以 HTML 標籤的方式輸出,瀏覽器能正常渲染

th:text 與 th:utext

HTML 代碼:

<body>
  <h2 th:text="' th:text &nbsp » ' + ${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

對於 URL 的處理是通過語法 @{…} 來處理的:

引用 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:hrefth: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} &gt; 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}  &gt; 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:ifth:unless 屬性進行條件判斷,下面的例子中,標籤只有在 th:if 中條件成立時才顯示:

<a th:href="@{/login}" th:if=${user == null}>Login</a>
<a th:href="@{/login}" th:unless=${user != null}>Login</a>

th:unlessth: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 參考手冊」解鎖更多技巧 🤪

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章