1. 程式人生 > >Spring Boot 整合 Thymeleaf 模板引擎

Spring Boot 整合 Thymeleaf 模板引擎

原文地址:Spring Boot 整合 Thymeleaf 模板引擎

Thymeleaf 是適用於 Web 和獨立環境的現代伺服器端 Java 模板引擎。

Thymeleaf 的主要目標是為開發帶來優雅的模板 - Thymeleaf 模板對於瀏覽器來說這些非HTML標準屬性在渲染的時候會被瀏覽器自動忽略,因此對於前端人員來說它就是一個靜態頁面;而後端通過 Thymeleaf 引擎渲染的時候這些標籤就會被識別,因此對於後端人員來說它又是動態頁面!。

快速開始

在 pom.xml 檔案新增 Thymeleaf 依賴

<dependency>
    <
groupId
>
org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

spring-boot-starter-thymeleaf 中包含了 spring-boot-starter-web 可以將其刪除。

Thymeleaf 相關配置

Thymeleaf 的模板檔案預設在 resources/templates 下,spring.thymeleaf.cache=false 開發時關閉快取,要不然修改模板檔案不能及時生效,需要重啟,生產環境可以開啟,

# thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.check-template-location=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

以上都是預設配置,當然也可以自定義配置。

編寫 controller

@Controller
public class ThymeleafController
{ @GetMapping(value = {"", "/", "index"}) public String index(Model model, HttpSession session) { // 網站標題 model.addAttribute("title", "dali`s Blogs"); // 登陸使用者 User loginUser = new User(2L, "admin", "admin", LocalDateTime.now()); session.setAttribute("login_user", loginUser); model.addAttribute("count", 20); // 使用者列表 List<User> users = new ArrayList<>(); users.add(new User(1L, "admin", "admin", LocalDateTime.now())); users.add(new User(2L, "dali", "dali", LocalDateTime.now())); model.addAttribute("users", users); return "index"; } }

編寫 Thymeleaf 模板檔案

resources/templates 目錄新建 index.html 檔案

<!DOCTYPE html>
<!-- 新增名稱空間 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>

    <!-- 變量表達式 ${...} -->
    <!-- 使用th:text標籤的值替換title標籤裡的值,title標籤裡的值只是為了給前端開發時做展示用的.這樣很好的做到了前後端分離 -->
    <!-- 獲取session、request中的資料 -->
    <title th:text="${title}">default title</title>
</head>
<body>

<!-- 訊息表示式 #{...}, 也稱為文字外部化、國際化或i18n -->
<span th:text="#{header.address.city}">...</span>

<!-- ${session.login_user} 獲取session的資料-->
<div th:object="${session.login_user}">
    <span th:text="*{userId}">...</span>
    <span th:text="*{username}">...</span>
    <span th:text="*{password}">...</span>
    <span th:text="*{createTime}">...</span>
</div>

<!-- 連結表示式@{…},類似的標籤有:th:href和th:src -->
<a th:href="@{https://rengangli.com}">絕對路徑</a>
<a th:href="@{/}">相對路徑</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,預設訪問resources/static下的css資料夾</a>

<!-- 字串替換 -->
<label th:text="'Welcome, ' + ${session.login_user.username} + '!'"></label>

<!-- 運算子 +,-,*,/,% -->
<label th:with="isEven=(${count} % 2 == 0)"></label>

<!-- 條件 -->
<!-- 標籤只有在th:if中條件成立時才顯示, th:unless相反,不成立時才顯示 -->
<a th:href="@{/login}" th:if="${session.login_user == null}">Login</a>

<!-- 條件語句 -->
<div th:switch="${session.login_user.username}">
    <p th:case="'admin'">login_user is an <span th:text="${session.login_user.username}"></span></p>
    <p th:case="'dali'">login_user is an <span th:text="${session.login_user.username}"></span></p>
    <!-- 預設屬性default可以用*表示 -->
    <p th:case="*">login_user is null</p>
</div>

<!-- 遍歷 -->
<table>
    <tr th:each="user : ${users}">
        <td th:text="${user.userId}">id</td>
        <td th:text="${user.username}">name</td>
        <td th:text="${user.password}">name</td>
        <td th:text="${user.createTime}">name</td>
    </tr>
</table>

<!-- Utility物件,內置於Context中,可以通過#直接訪問,包含#dates、#calendars、#numbers、#strings... -->
<label th:text="${#dates.createNow()}">#dates</label>

<!-- js中的表示式 -->
<script th:inline="javascript">
    var ctx = /*[[@{/}]]*/ '';
    var loginUser = /*[[${session.login_user.username}]]*/ '';
    alert(ctx);
    alert(loginUser);
</script>

</body>
</html>

效果圖

spring-boot-thymeleaf

參考資料

https://docs.spring.io/spring-boot/docs/1.5.16.RELEASE/reference/htmlsingle/

https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

本文所有程式碼放在 Github 上,地址:spring-boot-thymeleaf