5.5 Thymeleaf 页面布局(Thymeleaf 公共页面抽取)

本文介绍了Thymeleaf模板引擎中的页面布局技术,包括如何抽取公共页面片段、引用公共页面的片段表达式语法、可参数化片段的使用方法以及实战案例,展示了如何实现页面整体布局,从而提高开发效率。
摘要由CSDN通过智能技术生成

第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">
        &copy; 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">
        &copy; 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值