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

版权声明:本文为博主原创文章,未经博主允许也能转载,标明出处更好。 https://blog.csdn.net/fanpeizhong/article/details/88652828

应用场景:同一工程里不同页面所需使用的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},~{},~{})">   

猜你喜欢

转载自blog.csdn.net/fanpeizhong/article/details/88652828
今日推荐