• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

thymeleaf抽取公共页面

武飞扬头像
郝开
帮助1

在开发Web网站的时候,HTML页面有很多是相同的,如果每一个页面都写一遍,不仅非常麻烦,而且非常不利于后期的更改。典型的如导航栏、页脚等,每个HTML页面几乎都一样。

在Thymeleaf中我们通过如下的机制来抽取处公共的页面,并在需要的时候引入这个页面就可以了。

Thymeleaf中th:include、th:replace、th:insert、th:fragment用法及区别

标签 作用 写法
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment=“alert”></div>
th:include 布局标签,替换内容到引入的文件 <head th:include=“layout :: htmlhead” th:with=“title=‘xx’”></head>
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace=“fragments/header :: title”></div>
th:insert 布局标签,保留自己的主标签,保留替换内容的主标签 <div th:insert=“header :: title”></div>

th:include、th:replace、th:insert区别

th:include: 引入子模块的children,依然保留父模块的tag。 加载模板的内容: 读取加载节点的内容(不含节点名称),替换div内容
th:replace: 引入子模块的所有,不保留父模块的tag。 替换当前标签为模板中的标签,加载的节点会整个替换掉加载他的div

th:insert: 引入子模块的所有,保留自己的主标签,保留th:fragment的主标签

公共页面代码(子页面):
抽取公共页面common.html
学新通

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<body>
<!-- th:fragment 定义用于加载的块 -->
<span th:fragment="footer">
    it is test!
</span>
</body>
</html>

父页面引用公共页面代码:
commonPage/common表示公共页面common的路径

<!-- 保留自己的主标签,保留th:fragment的主标签。  -->
<div th:insert="commonPage/common::footer"></div>
<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的里面内容 -->
<div th:include="commonPage/common::footer">222</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载当前的<div>  -->
<div th:replace="commonPage/common::footer">333</div>

编译后:

<!-- 保留自己的主标签,保留th:fragment的主标签。  -->
<div><span>it is test!</span></div>

<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的里面内容 -->
<div> it is test!</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载当前的<div>  -->
<span>it is test!</span>

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhabkig
系列文章
更多 icon
同类精品
更多 icon
继续加载