Spring Boot Thymeleaf使用Layout Dialect裝飾模板。
Thymeleaf模板排版(layout)有兩種方式:
- Thymeleaf Standard Layout System的插入式layout,使用內建的
th:insert、th:replace、th:include插入片段到模板中。 - Thymeleaf Layout Dialect的繼承式layout,要另外匯入
thymeleaf-layout-dialect函式庫,使用layout:fragment、layout:decorate等來裝飾模板。
下面介紹如何使用Thymeleaf Layout Dialect。
範例環境:
- Java 8
- Spring Boot 2.3.2.RELEASE
- Thymeleaf 3
- Thymeleaf Layout Dialect 2
事前要求
參考「Spring Boot Thymeleaf 簡單範例」搭建好Spring Boot Thymeleaf專案,下面以此進行修改。
Layout Dialect範例
在pom.xml加入thymeleaf-layout-dialect依賴。
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
在src/main/resources/templates新增layout.html內容如下,用來"裝飾"hello.html的模板。
在layout.html的<html>加入thyemleaf layout的xml命名空間xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"以便使用layout dialect的屬性。
在<head>中加入了Bootstrap CDN的css。
在<div>使用layout:fragment標示片段的名稱為content,此名稱對到hello.html中帶有layout:fragment="content"的標籤並把內容套進來。
layout.html
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel='stylesheet' type="text/css"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<title>Layout</title>
</head>
<body>
<header>
<p>Hello Thymeleaf Layout Dialect</p>
</header>
<div layout:fragment="content">
</div>
</body>
</html>
修改hello.html如下。一樣在<html>加入layout dialect的xml命名空間,使用layout:decorate="~{layout.html}"標註使用的裝式模板為layout.html。
在<head>中加入/css/hello.css。
在要套用裝飾模板的標籤加上layout:fragment屬性指定裝飾模板中同名的屬性,即對應到layout.html中帶有layout:fragment="content"的標籤。
hello.html
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout.html}">
<head>
<link rel='stylesheet' th:href="@{/css/hello.css}">
<title>Hello Thymeleaf</title>
</head>
<body>
<div layout:fragment="content">
<p th:text="'Hello, ' + ${name} + '!'"/>
</div>
</body>
</html>
測試
啟動專案並輸入http://localhost:8080/demo/hello導向hello.html結果顯示如下。可以看到<head>的內容除了hello.html原有的還加上(繼承)了layout.html的內容。hello.html的layout:fragment="content"標籤內容則被放入了layout.html的layout:fragment="content"標籤位置。
<html>
<head>
<title>Hello Thymeleaf</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/demo/css/hello.css">
</head>
<body>
<header>
<p>Hello Thymeleaf Layout Dialect</p>
</header>
<div>
<p>Hello, World!</p>
</div>
</body>
</html>
參考github。
沒有留言:
張貼留言