Skip to content

th:insert与th:replace的区别

th:insertth:replace 是 Thymeleaf 引入模板片段的两个核心属性,核心差异在于片段与宿主标签的融合方式

1. 核心定义

属性行为描述
th:insert将指定片段插入到宿主标签的内容区域(宿主标签保留,片段作为其子元素)
th:replace用指定片段替换整个宿主标签(宿主标签消失,片段直接替代它)

假设有如下HTML片段:

html
<!-- 定义名为 copy 的片段,根标签是 footer -->
<footer th:fragment="copy">
  &copy; 2011 The Good Thymes Virtual Grocery
</footer>

分别用 insert/replace 引入片段

html
<body>
  <!-- 页面主体内容 -->
  ...

  <!-- 用 th:insert 引入 -->
  <div th:insert="~{footer :: copy}"></div>

  <!-- 用 th:replace 引入 -->
  <div th:replace="~{footer :: copy}"></div>
</body>

最终渲染结果

html
<body>
  ...

  <!-- th:insert 结果:宿主 div 保留,片段作为子元素 -->
  <div>
    <footer>
      &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
  </div>

  <!-- th:replace 结果:宿主 div 被片段的 footer 标签替换 -->
  <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
  </footer>
</body>

关键细节补充

  • 简化写法兼容:两者都支持省略片段表达式的 ~{},简写为 th:insert="footer :: copy" / th:replace="footer :: copy"
  • 属性继承:如果宿主标签有额外属性(如 class/style),th:insert 会保留这些属性(因为宿主标签还在),而 th:replace 会丢失(因为宿主标签被替换):
    html
    <!-- th:insert 保留 class="box" -->
    <div class="box" th:insert="footer :: copy"></div>
    <!-- 渲染结果:<div class="box"><footer>...</footer></div> -->
    
    <!-- th:replace 丢失 class="box" -->
    <div class="box" th:replace="footer :: copy"></div>
    <!-- 渲染结果:<footer>...</footer> -->
  • 使用场景
    • th:insert:需要保留宿主标签的场景(如给片段加容器样式、统一布局);
    • th:replace:需要片段直接作为独立元素的场景(如替换页面原生的 footer 标签、保持 HTML 结构简洁)。

额外补充:th:include(已废弃)

Thymeleaf 3.x 中已废弃 th:include(仅保留 insert/replace),它的行为是「插入片段的内容,丢弃片段的根标签」,对比参考:

html
<!-- 废弃的 th:include 效果 -->
<div th:include="footer :: copy"></div>
<!-- 渲染结果:<div>&copy; 2011 The Good Thymes Virtual Grocery</div> -->

总结

  1. th:insert 保留宿主标签,将片段作为子元素插入;th:replace 替换宿主标签,片段直接替代宿主;
  2. 宿主标签的属性在 th:insert 中保留,在 th:replace 中丢失;
  3. 按需选择:需容器包裹用 insert,需简洁结构用 replace