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

Thymeleaf中页面布局

首先,几个标签的定义

th:fragment布局标签,定义一个代码片段,方便其它地方引用<div th:fragment="alert">
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="layout :: htmlhead" 中,layout为页面文件名,htmlhead为该文件中 th:fragment的值。

             th:replace 、th:insert  同上。

th:include、th:replace、th:insert类似,但是区别如下:

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

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

 

用代码简单的测试一下

公共页面代码(子页面):

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

父页面代码:

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

编译后:

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

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

 


版权声明:本文为spurs611原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。