thymeleaf:如何在引入fragment时保留部分差异内容(保留原内容)

应用场景:同一工程里不同页面所需使用的script文件和css文件大同小异,若每页都写一遍,修改时成本很高,故设置一公共的head文件,再导入它。

thymeleaf使用fragment语法进行导入。使用简介如下:

定义公共fragment:

<footer th:fragment="copy">  
   the content of footer 
</footer>

引入公共fragment:

  1. th:insert:保留自己的主标签,保留th:fragment的主标签。
  2. th:replace:不要自己的主标签,保留th:fragment的主标签。
  3. th:include:保留自己的主标签,不要th:fragment的主标签。(官方3.0后不推荐)
导入片段:
<div th:insert="footer :: copy"></div>  

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

<div th:include="footer :: copy"></div>

结果为:
<div>  
    <footer>  
       the content of footer   
    </footer>    
</div>    

<footer>  
    the content of footer 
</footer>    

<div>  
    the content of footer 
</div>  

但以上方式都会替换原标签的内容。而我们的head标签虽大同小异,但毕竟也有不一样的地方,如至少定义不同的title元素。解决办法有两个,使用fragment的参数,以及它的lexible layouts特性

参数的示例:

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>


<div th:replace="::frag (${value1},${value2})">...</div>
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>
可以不按照参数定义的顺序
<div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>、

lexible layouts特性:

定义:

<head th:fragment="head(title,links,scripts)">  
<title th:replace="${title}">The awesome application</title>  

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  

<th:block th:replace="${links}" />  
<th:block th:replace="${scripts}" />  

</head>  

引入:

<head th:include="include/header :: head(~{::title},~{::link},~{::script})">   
<title>html的title</title>  
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">  
<script th:src="@{/js/bootstrap.js}"></script>  
</head>  

如果没有定义link,可写~{}

<head th:include="include/header :: head(~{::title},~{},~{})">   

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值