Thymeleaf Layout Fragments: th:insert vs th:replace Compared
When to use th:insert versus th:replace in Thymeleaf layouts, and how each affects the natural-template HTML property.
15 Jul 2025, 22:18 UTC

Problem: Fragments that don't merge as expected
Thymeleaf developers often encounter situations where th:insert leaves the wrapper tag in place, or th:replace removes it unexpectedly, especially when the template is previewed in a browser without the server running. Understanding the distinction is key to keeping your HTML valid and your renders predictable.
The natural template advantage
Thymeleaves design goal is the natural template: a template that remains valid HTML even without a processor running. This means you can open a Thymeleaf file in any browser and see a sensible static layout. When you add th:insert or th:replace, the attribute must not break that property. Both attributes are designed to preserve validity, but they operate at different points in the element tree.
th:insert vs th:replace
- th:insert places the fragments content inside the target element. The wrapper tag remains in the output.
- th:replace replaces the entire target element with the fragments output. The wrapper tag is removed.
Worked example: modular header
Create a file src/main/resources/templates/fragments/header.html:
<th:fragment="main"><h1>My Application</h1><nav><a href="/">Home</a></nav></th:fragment>In a page index.html, include the fragment:
<header th:replace="~{fragments/header :: main}"></header>Verification in practice
- Start your Spring Boot application (Java 17, Spring Boot 3.2, Thymeleaf 3.1+).
- Navigate to the page in a browser and view the page source.
- With th:replace, the header tag should be absent; its contents appear in its place.
- With th:insert, the header tag will enclose the inserted content.
- If the output differs, verify the fragment path and that the th:fragment name matches the :: selector.
Limitations and trade-offs
- Dependency scope: Full fragment support requires the Thymeleaf Spring dialect; without it, some attribute behaviors differ.
- Element restrictions: th:replace cannot be applied to html, head, or body in certain configurations.
- Testability: Embedding excessive presentation logic in fragments makes unit testing harder; keep fragments focused on structure.
- Server-only resolution: Fragment resolution via ~{} paths depends on the servlet context; file-only previews may not resolve correctly.
Actionable closing
Next time you add a layout fragment, ask yourself whether you need a wrapper element or seamless substitution. Use th:replace for the latter and th:insert when the wrapper semantics matter. Render, check the source, and adjust the attribute to match your layout intent.