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>

 

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值