Thymeleaf中th:include和th:replace的使用和区别

Thymeleaf一般基于springboot来使用,其实是springmvc。

其实在日常中我们编写网页代码,常常会编写网页头和底部。

但是不可能每个页面都Ctrl+C,Ctrl+V。这样会反复的代码编写。

另外涉及到一些多重复的代码:如对于thymeleaf分页的代码很多都是重复的,所以不可能都是几个页面全是重复的代码。

所以我们最好将重复的代码写在多个html中,需要的时候放进页面中。

所以便用到了th:include和th:replace

下面来说说他们的用法和区别:

首先我们pom.xml添加依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

将重复的信息单独封装成一个footer.html

<!DOCTYPE html SYSTEM "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>
	<div class="panelBar" th:fragment="footer">
           <!--下面是通用的部分-->
           <div>
            this is test!    
           <div>
	</div>
    </body>
</html>

调用:

<div th:replace="footer::footer"></div>

其中footer::footer中第一个为文件名,第二个为th:fragment中的值。

 

th:include的用法也跟th:replace类似。但是区别

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

例子:

<!-- 模版 -->
<!-- th:fragment 定义用于加载的块 -->
<span th:fragment="footer"> 
    it is test!
</span>

两种的引用

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

调用之后的结果

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值