Thymeleaf公共代码段抽取,th:include, th:replace, th:insert

本文参考: Thymeleaf教程

th:include  将公共代码片段包含的内容插入到使用该属性的标签
th:insert  将公共代码片段插入到使用该属性的标签
th:replace  将公共代码片段直接替换使用该属性的标签

 

 

 

 

  • 引入代码段:

使用以上3个属性引入代码片段,都可以使用以下两种方式实现:

  • ~{templateName::selector}   模板名::选择器名
  • ~{templateName::fragmentname}  模板名::片段名

通常情况下~{}可以省略,其行内写法 [[~{...}]] 或 [(~{...})], 其中 [[~{...}]] 会转义特殊字符, [(~{...})] 不会转义特殊字符

 

新建一个common.html文件,写入以下代码:

1 <div th:fragment="cf" id="fragment_id" >
2         <span>公共代码段</span>
3     </div>

引入代码段:

 1 <!-- th:include 通过片段名引入 -->
 2     <div th:include="common::cf"></div>
 3     <!-- th:include 通过 id 选择器引入 -->
 4     <div th:include="common::#fragment_id"></div>
 5     
 6     <!-- th:insert 通过片段名引入 -->
 7     <div th:insert="common::cf"></div>
 8     <!-- th:insert 通过 id 选择器引入 -->
 9     <div th:insert="common::#fragment_id"></div>
10     
11     <!-- th:replace 通过片段名引入 -->
12     <div th:replace="common::cf"></div>
13     <!-- th:replace 通过 id 选择器引入 -->
14     <div th:replace="common::#fragment_id"></div>

结果为:

 

  •  参数传递:

  引入公共代码片段时,我们可以使用以下两种方式传递参数:

  •   模板名::片段名或选择器名(参数1=值1,参数2=值2,,...)
  •        模板名::片段名或选择器名(值1, 值2,...)

common.html代码:

 

1 <div th:fragment="cf(var1, var2)" id="fragment_id" >
2         <span th:text=" 'var1:'+${var1}+ '-----var2:'+${var2} "></span>
3     </div>

 

引入代码段html:

 1 <!-- th:include 通过片段名引入 -->
 2     <div th:include="common1::cf(var1='include_name', var2='include_name2')"></div>
 3     <!-- th:include 通过 id 选择器引入 -->
 4     <div th:include="common1::#fragment_id('include_id', 'include_id2')"></div><br/>
 5     
 6     
 7     
 8     <!-- th:insert 通过片段名引入 -->
 9     <div th:insert="common1::cf(var1='insert_name', var2='insert_name2')"></div>
10     <!-- th:insert 通过 id 选择器引入 -->
11     <div th:insert="common1::#fragment_id('insert_id', 'insert_id2')"></div><br/>
12     
13     
14     
15     <!-- th:replace 通过片段名引入 -->
16     <div th:replace="common1::cf(var1='replace_name', var2='replace_name2')"></div>
17     <!-- th:replace 通过 id 选择器引入 -->
18     <div th:replace="common1::#fragment_id('replace_id', 'replace_id2')"></div><br/>

结果:

 

posted @ 2022-03-08 17:12  基地您  阅读(411)  评论(0编辑  收藏  举报