thymeleaf抽取公共页面
在开发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>