首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 整合 Thymeleaf 模板引擎完整指南

     編輯:Java 相關知識

為什麼選擇 Thymeleaf?

Thymeleaf 是 Spring Boot 官方推薦的伺服端 Java 模板引擎。其最大特色是原生 HTML 相容:模板屬性以 th:* 形式內嵌於標準 HTML 標籤中,瀏覽器直接開啟即可預覽靜態頁面,前端開發者無需啟動後端即可進行樣式調整,極大提升協作效率。

基本語法範例

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>

模板宣告與命名空間

<html xmlns="https://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
  ...
</html>

宣告 th 命名空間,所有 Thymeleaf 屬性皆在該命名空間下。

靜態資源載入:雙路徑策略

<link rel="stylesheet" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  • 無後端渲染時:瀏覽器識別 href,按相對路徑載入,IDE 亦可提供提示。
  • 有後端渲染時:Thymeleaf 以 th:href 取代 href,產出專案相對路徑 /css/gtvg.css,伺服器正確定位資源。

注意:路徑表達式使用 @{...},變數引用才用 ${...}。

國際化與常量渲染

  1. 建立 messages.properties(或 messages_zh_TW.properties):
    title=這是標題
  2. application.properties 註冊:
    spring.messages.basename=messages
  3. 模板使用:
    <title th:text="#{title}"></title>

變數渲染

Controller 傳遞:

@Controller
public class IndexController {
    @GetMapping({"/", "index"})
    public String index(Model model) {
        model.addAttribute("var1", "value1");
        model.addAttribute("src1", "https://www.baidu.com");
        Map<String, Object> map = new HashMap<>();
        map.put("src1", "/a.png");
        map.put("src2", "/b.png");
        model.addAttribute("src", map);
        return "index";
    }
}

模板取用:

<span th:text="${var1}"></span>
<a th:href="${src1}">baidu</a>
<img th:src="${src.src1}" />

流程控制

迴圈

<div th:each="value: ${list}" th:text="${value}"></div>

條件判斷

<div th:if="${judge}">顯示內容</div>
<div th:unless="${judge}">否則顯示</div>

Switch 選擇

<div th:switch="${user.role}">
  <p th:case="'admin'">管理員</p>
  <p th:case="#{roles.manager}">經理</p>
</div>

注意:th:case 中的字串常值需加單引號。

片段引用與參數傳遞

footer.html 定義片段:

<div th:fragment="copy">footer</div>

index.html 引用:

<div th:include="footer :: copy" th:with="param=${value}">index</div>
  • include:保留外層標籤,片段內容插入內部。
  • replace:整個標籤被片段取代。
  • th:with:傳遞區域變數至片段。

JavaScript 內嵌變數

<script th:inline="javascript">
/*<![CDATA[*/
var username = /*[[${session.user.name}]]*/ 'Sebastian';
/*]]>*/
</script>
  • 必須加 th:inline="javascript"。
  • 使用 /*[[...]]*/ 包裹變數,並提供預設值,確保無後端時前端仍可運行。
  • CDATA 區塊避免特殊字元(如 < >)導致 JS 語法錯誤。

總結

Thymeleaf 以自然模板特性、強大的表達式語法、靈活的片段復用與完善的 JS 整合,成為 Spring Boot 專案的首選視圖技術。掌握上述核心用法即可應對絕多數業務場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved