SpringBoot -- Thymeleaf页面模板实现公共页面元素抽取

本文介绍了SpringBoot中利用Thymeleaf页面模板技术进行公共页面元素抽取的原因和方法,包括如何通过th:insert、th:replace和th:include属性实现公共片段的插入、替换和包含,并提供了传入参数的两种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thymeleaf页面模板实现公共页面元素抽取

一、公共页面抽取的原因
       我们在做一个完成的系统时,需要用到很多页面,而页面之间比如菜单栏,导航栏等这些模块是每个页面当中的一部分,如果重复写,会使页面看起来繁琐,代码量占用大,而我们需要的是尽可能的使用少量代码,精简的写出全部功能,因此需要将公共页面抽取出来,其中我们使用的是Thymeleaf页面模板技术,Thymeleaf是SpringBoot官方所推荐使用的。


二、如何实现公共页面抽取
       1.如下是Thymeleaf官方文档内容,解释了如何去实现公共页面抽取。Thymeleaf官方文档

1、抽取公共片段
<div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名
模板名:唯一一个保留公共页面模块的页面

3、默认效果:
	insert的公共片段在div标签中
	如果使用th:insert等属性进行引入,可以不用写~{}:
	行内写法可以加上:[[~{}]];[(~{})];

       2.三种引入公共片段的th属性:

         th:insert:将公共片段整个 插入 到声明引入的元素中

         th:replace:将声明引入的元素 替换 为公共片段(推荐使用这一种,页面元素与原来不变,即不增加了div,也不会将原来的元素去掉)

         th:include:将被引入的片段的 内容 包含 进这个标签中

<footer th:fragment="copy">
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>

引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

效果
<div>
    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>

<footer>
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<div>
	&copy; 2011 The Good Thymes Virtual Grocery
</div>

       3.引入片段的时候传入参数:
              1)当我们使用 id 去标识时,则相当于选择了
~{templatename::selector}:模板名::选择器 这一种方式,则引入参数时使用<div th:replace="模板名::#id" ></div>
              2) 第二种方式<nav th:fragment="tnav"></nav> <div th:replace="~{模板名::tnav}"></div>

<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">
<!-- 当使用id时,则选择了
~{templatename::selector}:模板名::选择器 这一种方式-->
   
<!--引入侧边栏;传入参数-->
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>

三、 我对于抽取公共页面模块这一个用得真心觉得不错,减少了我们很多的代码量,让我们的页面看起来不会冗余,精简,能够及时看到核心部分,而且这个学起来就几分钟的事情,大家有空就多学一点知识,一起加油吧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值