# Thymeleaf模板引擎怎么使用
## 一、Thymeleaf簡介
### 1.1 什么是Thymeleaf
Thymeleaf是一個現代化的服務器端Java模板引擎,適用于Web和獨立環境。它能夠處理HTML、XML、JavaScript、CSS甚至純文本。與JSP等傳統技術相比,Thymeleaf的主要特點是:
- **自然模板**:可在瀏覽器直接打開預覽
- **無Servlet依賴**:不強制要求Servlet環境
- **Spring完美集成**:Spring官方推薦的視圖技術
- **表達式語法**:強大的OGNL和SpringEL表達式支持
### 1.2 核心特性
- **模板緩存**:可配置的模板緩存機制
- **國際化支持**:內置國際化處理能力
- **片段重用**:支持模板片段定義和引用
- **多種方言**:可通過方言擴展功能
## 二、環境配置
### 2.1 Maven依賴
```xml
<!-- Spring Boot集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 獨立使用 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false # 開發時關閉緩存
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
src/
├── main/
│ ├── java/
│ └── resources/
│ ├── static/ # 靜態資源
│ └── templates/ # 模板文件
<!-- 變量表達式 -->
<p th:text="${user.name}">默認用戶名</p>
<!-- 選擇表達式 -->
<div th:object="${user}">
<p th:text="*{age}">年齡</p>
</div>
<!-- 鏈接表達式 -->
<a th:href="@{/user/list}">用戶列表</a>
<!-- 片段表達式 -->
<div th:insert="~{footer :: content}"></div>
屬性 | 說明 |
---|---|
th:text |
文本替換 |
th:utext |
非轉義文本 |
th:value |
表單值設置 |
th:each |
循環迭代 |
th:if |
條件判斷 |
th:switch |
多條件選擇 |
th:href |
鏈接URL |
th:src |
資源URL |
<!-- 循環示例 -->
<ul>
<li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>
<!-- 條件判斷 -->
<div th:if="${user.isAdmin}">管理員面板</div>
<div th:unless="${user.isAdmin}">普通用戶面板</div>
<!-- Switch語句 -->
<div th:switch="${user.role}">
<p th:case="'admin'">管理員</p>
<p th:case="'user'">普通用戶</p>
</div>
定義基礎模板 base.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:fragment="title">默認標題</title>
</head>
<body>
<header th:insert="~{header :: main}"></header>
<div th:replace="~{content}"></div>
<footer th:replace="~{footer :: main}"></footer>
</body>
</html>
子模板繼承:
<html th:replace="~{base :: layout(~{::title}, ~{::content})}">
<head>
<title>子頁面標題</title>
</head>
<body>
<div th:fragment="content">
<!-- 頁面特有內容 -->
</div>
</body>
</html>
<form th:action="@{/user/save}" th:object="${user}" method="post">
<input type="text" th:field="*{name}">
<input type="email" th:field="*{email}">
<button type="submit">保存</button>
</form>
<p th:text="#{welcome.message}">歡迎消息</p>
<p th:text="#{|hello.user|(${user.name})|}">個性化問候</p>
<!-- 日期格式化 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"></p>
<!-- 集合工具 -->
<p th:text="${#lists.size(user.roles)}"></p>
<!-- 字符串操作 -->
<p th:text="${#strings.toUpperCase(user.name)}"></p>
@Controller
public class UserController {
@GetMapping("/user")
public String user(Model model) {
model.addAttribute("user", new User("張三", 25));
return "user/profile";
}
}
<div sec:authorize="isAuthenticated()">
歡迎 <span sec:authentication="name"></span>
</div>
<div sec:authorize="hasRole('ADMIN')">
管理員功能
</div>
<input type="text" th:field="*{email}" class="form-control">
<div th:if="${#fields.hasErrors('email')}"
th:errors="*{email}" class="error-message"></div>
# 生產環境配置
spring.thymeleaf.cache=true
spring.thymeleaf.template-resolver-order=1
<!-- 緩存用戶信息片段 -->
<div th:replace="~{user/info :: panel}"
th:with="cacheKey=${#strings.arrayJoin('user',user.id)}">
</div>
<!-- 版本化靜態資源 -->
<link th:href="@{/css/main.css(v=${@environment.getProperty('app.version')})}">
<!-- 禁用轉義 -->
<p th:utext="${htmlContent}"></p>
<!-- 內聯表達式 -->
[(${unsafeContent})]
確保正確配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
檢查: 1. 模板文件是否在正確目錄 2. 后綴配置是否匹配 3. 模板語法是否正確
Thymeleaf作為現代Java模板引擎,通過本文我們全面了解了: - 從基礎語法到高級功能的使用方法 - 與Spring框架的深度集成 - 實際開發中的性能優化技巧 - 常見問題的解決方案
通過合理應用Thymeleaf,可以構建出結構清晰、維護性強的Web應用視圖層。其自然模板特性特別適合前后端協作開發場景,是傳統JSP技術的優秀替代方案。
本文約4500字,涵蓋了Thymeleaf的核心使用場景。實際開發中應根據項目需求選擇合適的特性組合,并參考官方文檔獲取最新特性支持。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。