使用Thymeleaf构建通用布局页面
Thymeleaf通过布局方言(Layout Dialect)或片段(Fragments)实现页面复用。以下是两种核心方法:
一、使用Thymeleaf布局方言
1. 添加依赖
需在项目中引入Thymeleaf和布局方言的依赖(如Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>3.2.0</version>
</dependency>
2. 定义基础模板
创建base.html作为布局模板,使用layout:fragment标记可替换区域:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">Default Title</title>
</head>
<body>
<header>
<h1>Shared Header</h1>
</header>
<div layout:fragment="content">
<!-- 默认内容(可被页面覆盖) -->
</div>
<footer>
<p>Shared Footer</p>
</footer>
</body>
</html>
3. 继承布局的页面
子页面通过layout:decorate继承布局,并填充片段内容:
<html layout:decorate="~{base}" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page Title</title>
</head>
<body>
<div layout:fragment="content">
<h2>Page Content</h2>
<p th:text="${variable}">Dynamic Data</p>
</div>
</body>
</html>
二、使用Thymeleaf片段(Fragments)
1. 定义可复用片段
在fragments.html中声明公共部分:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="header">
<header>Shared Header</header>
</th:block>
<th:block th:fragment="footer">
<footer>Shared Footer</footer>
</th:block>
</body>
</html>
2. 在页面中引入片段
通过th:insert或th:replace动态插入:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:insert="~{fragments :: header}"></div>
<main>Page Content</main>
<div th:replace="~{fragments :: footer}"></div>
</body>
</html>
三、动态参数传递
片段支持参数化,增强灵活性:
<!-- 定义带参数的片段 -->
<th:block th:fragment="greeting(name)">
<p>Hello, <span th:text="${name}">User</span>!</p>
</th:block>
<!-- 调用时传递参数 -->
<div th:insert="~{fragments :: greeting(${user.name})}"></div>
四、总结
布局方言(Layout Dialect)或片段(Fragments)区别
- 布局方言:适合整体页面结构继承(如HTML骨架)。
- 片段:适合模块化复用(如导航栏、弹窗组件)。
根据项目需求选择合适方式,或混合使用两者。
991

被折叠的 条评论
为什么被折叠?



