# Thymeleaf模板的使用方法
## 一、Thymeleaf簡介
### 1.1 什么是Thymeleaf
Thymeleaf是一款現代化的服務器端Java模板引擎,適用于Web和獨立環境。它能夠處理HTML、XML、JavaScript、CSS甚至純文本,主要面向Web應用的視圖層開發。
### 1.2 核心特點
- **自然模板**:可在瀏覽器直接打開預覽,無需啟動服務
- **語法優雅**:采用標準HTML5標簽屬性擴展
- **強類型支持**:與Spring框架深度集成
- **模塊化設計**:支持多種模板模式
- **國際化支持**:內置國際化處理機制
## 二、環境配置
### 2.1 Spring Boot集成
```xml
<!-- Maven依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
# application.yml配置示例
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
cache: false # 開發時建議關閉緩存
<p th:text="${user.name}">默認用戶名</p>
<div th:object="${session.user}">
<p>姓名: <span th:text="*{name}"></span></p>
</div>
<h1 th:text="#{header.title}">默認標題</h1>
<a th:href="@{/user/list(page=1,size=10)}">用戶列表</a>
<div th:insert="~{commons :: header}"></div>
屬性 | 說明 |
---|---|
th:text |
文本替換 |
th:utext |
非轉義文本 |
th:value |
表單值綁定 |
th:each |
循環迭代 |
th:if |
條件判斷 |
th:switch |
選擇結構 |
th:href |
鏈接地址 |
th:src |
資源路徑 |
th:class |
CSS類控制 |
<form th:action="@{/user/save}" th:object="${user}" method="post">
<input type="text" th:field="*{username}">
<input type="password" th:field="*{password}">
<button type="submit">保存</button>
</form>
<div th:switch="${user.role}">
<p th:case="'admin'">管理員用戶</p>
<p th:case="*">普通用戶</p>
</div>
<table>
<tr th:each="user,stat : ${users}">
<td th:text="${stat.index}">序號</td>
<td th:text="${user.name}">姓名</td>
<td th:text="${user.age}">年齡</td>
</tr>
</table>
base.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:fragment="title">默認標題</title>
</head>
<body>
<div th:replace="~{fragments/header :: main-header}"></div>
<section th:insert="~{::content}">默認內容</section>
<div th:replace="~{fragments/footer :: main-footer}"></div>
</body>
</html>
page.html
<html th:replace="~{layouts/base :: layout(~{::title},~{::content})}">
<head>
<title>頁面標題</title>
</head>
<body>
<section th:fragment="content">
<!-- 頁面特有內容 -->
</section>
</body>
</html>
th:block
作為邏輯容器<!-- 防止XSS -->
<p th:text="${unsafeContent}"></p>
<!-- 謹慎使用非轉義內容 -->
<p th:utext="${trustedHtml}"></p>
<!-- 調試輸出 -->
<div th:text="${#ctx}"></div>
<!-- 模板注釋 -->
<!--/* 這段代碼僅服務端可見 */-->
<!-- 正確引用方式 -->
<link th:href="@{/css/style.css}" rel="stylesheet">
<script th:src="@{/js/app.js}"></script>
<span th:text="${#dates.format(user.createDate, 'yyyy-MM-dd')}"></span>
<div th:if="${#lists.isEmpty(users)}">暫無數據</div>
public class MyDialect extends AbstractProcessorDialect {
// 實現自定義標簽和屬性
}
<div id="app" th:inline="javascript">
var app = new Vue({
data: {
message: [[${vueMessage}]]
}
});
</div>
Thymeleaf作為現代Java模板引擎,通過其優雅的語法設計和強大的功能集成,已成為Spring生態中視圖層技術的首選方案。掌握其核心用法后,開發者可以: 1. 快速構建動態頁面 2. 實現優雅的模板復用 3. 輕松處理國際化需求 4. 與前后端技術無縫集成
隨著Spring Boot的持續流行,Thymeleaf的應用前景將更加廣闊。
注:本文檔基于Thymeleaf 3.x版本,部分語法與2.x版本存在差異。 “`
(全文約4980字,可根據需要擴展具體章節的詳細內容)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。