第5章 Thymeleaf 模板引擎
5.1 Thymeleaf 入门
5.2 Thymeleaf 表达式
5.3 Thymeleaf 表达式的语法
5.4 Thymeleaf 的高级用法
5.5 Thymeleaf 页面布局
5.5 Thymeleaf 页面布局(Thymeleaf 公共页面抽取)
5.5.1 引入代码片段(简单案例)
在模板中经常希望包含来自其他模板页面的内容,如页脚、页眉、菜单等。为了做到这一点,Thymeleaf 提供了th:fragment
属性。下面通过在页面中添加标准的版权页脚的场景来演示如何引入代码片段。
1、抽取公共页面(定义版权页脚代码片段)。
用法:
<div th:fragment="copyright">
© 2020 Thymeleaf footer
</div>
footer.html(位置:src/main/resources/templates/footer.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>copyright</title>
</head>
<body>
<div th:fragment="copyright">
© 2020 The Thymeleaf footer
</div>
</body>
</html>
2、 引用公共页面(引入代码片段模板)。
用法:
<div th:insert="~{footer::copyright}"></div>
通常情况下,~{} 可以省略,简写成:
<div th:insert="footer::copyright"></div>
layout.html(位置:src/main/resources/templates/layout.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>页面布局</title>
</head>
<body>
<h1>Thymeleaf 模板引擎</h1>
<h3>页面布局</h3>
<div th:insert="~{footer::copyright}"></div>
<!--<div th:insert="footer::copyright"></div>-->
</body>
</html>
3、启动验证。
启动项目后,在浏览器中输入地址 http://localhost:8080/layout, 验证主页是否能正常引入 foot.html 中的代码片段,如图所示。
5.5.2 片段表达式语法规范(引用公共页面)
1、~{templatename::fragmentname}:模板名::片段名
<!--th:insert 片段名引入--> <div th:insert="commons::fragment-name"></div>
备注:通常情况下,~{} 可以省略。
2、~{templatename::selector}:模板名::选择器
<!--th:insert id 选择器引入--> <div th:insert="commons::#fragment-id"></div>
备注:通常情况下,~{} 可以省略。
3、th:insert、th:replace、th:include 的区别?
在 Thymeleaf 中,我们可以使用以下 3 个属性,将公共页面片段引入到当前页面中。
- th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
- th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
- th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。
示例:
(1)抽取公共页面
common.html<div th:fragment="fragment-name" id="fragment-id"> <span>公共页面片段</span> </div>