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 亦可提供提示。th:href 取代 href,產出專案相對路徑 /css/gtvg.css,伺服器正確定位資源。注意:路徑表達式使用 @{...},變數引用才用 ${...}。
messages.properties(或 messages_zh_TW.properties):title=這是標題application.properties 註冊:spring.messages.basename=messages<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>
<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:傳遞區域變數至片段。<script th:inline="javascript">
/*<![CDATA[*/
var username = /*[[${session.user.name}]]*/ 'Sebastian';
/*]]>*/
</script>
th:inline="javascript"。/*[[...]]*/ 包裹變數,並提供預設值,確保無後端時前端仍可運行。CDATA 區塊避免特殊字元(如 < >)導致 JS 語法錯誤。Thymeleaf 以自然模板特性、強大的表達式語法、靈活的片段復用與完善的 JS 整合,成為 Spring Boot 專案的首選視圖技術。掌握上述核心用法即可應對絕多數業務場景。