Thymeleaf页面模板实现公共页面元素抽取
一、公共页面抽取的原因
我们在做一个完成的系统时,需要用到很多页面,而页面之间比如菜单栏,导航栏等这些模块是每个页面当中的一部分,如果重复写,会使页面看起来繁琐,代码量占用大,而我们需要的是尽可能的使用少量代码,精简的写出全部功能,因此需要将公共页面抽取出来,其中我们使用的是Thymeleaf页面模板技术,Thymeleaf是SpringBoot官方所推荐使用的。
二、如何实现公共页面抽取
1.如下是Thymeleaf官方文档内容,解释了如何去实现公共页面抽取。Thymeleaf官方文档
1、抽取公共片段
<div th:fragment="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">
© 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>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 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>
三、 我对于抽取公共页面模块这一个用得真心觉得不错,减少了我们很多的代码量,让我们的页面看起来不会冗余,精简,能够及时看到核心部分,而且这个学起来就几分钟的事情,大家有空就多学一点知识,一起加油吧。