Thymeleaf

fragment 类似jsp的tag,可以用于抽取重复代码模板,定义组件,并且可以朝fragment中传递参数,较为灵活。

参考原文: https://blog.csdn.net/believe__sss/article/details/79992408

定义模块, 在component目录下定义pagination.html 作为组件模板,用作公共代码抽取:

<!-- th:fragment 定义用于加载的块 -->
<!DOCTYPE html "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<span th:fragment="pagination">
the public pagination
</span>
</body>
</html>

在根路径下创建 index.html,引用上述模块文件:

================= th:include 和 th:replace============================
<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的内容 -->
<div th:include="component/pagination::pagination">1</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载他的<div>  -->
<div th:replace="component/pagination::pagination">2</div>

执行结果:

<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的内容 -->
<div> the public pagination</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载他的<div>  -->
<span> the public pagination</span>
  • th:include:加载模板的内容: 读取加载节点的内容(不含节点名称),替换div内容

  • th:replace:替换当前标签为模板中的标签,加载的节点会整个替换掉加载他的div

最后更新于