Understanding Fragment Inclusion
Thymeleaf gives you three ways to include fragments: th:insert, th:replace, and th:include. Each behaves slightly differently, so let's break them down.
All three reference the same fragment, but they'll produce different HTML output.
th:insert vs th:replace
th:insert keeps the host tag and puts the fragment inside it. th:replace replaces the host tag entirely with the fragment.
If the fragment is <footer>...</footer>, th:insert gives you <div><footer>...</footer></div>, while th:replace gives you just <footer>...</footer>.
th:include Behavior
th:include includes only the content inside the fragment tag, not the tag itself.
If the fragment is <div class="sidebar">...content...</div>, you get just the inner content without the wrapping div.
Fragment Selection with ~{}
The ~{} syntax is how you select fragments. You specify the file and the fragment name.
The format is ~{file :: fragment-name}. Thymeleaf looks for the fragment in the specified file.
Partial Fragments
You can define multiple fragments in a single file and select specific ones.
Now you can include either fragment separately using ~{file :: fragment-name}.
Dynamic Fragment Names
You can use expressions to dynamically select fragments based on conditions.
This lets you switch between different templates at runtime based on the templateName variable.
Choosing the Right Method
Use th:replace when you want to completely replace the host tag. Use th:insert when you want to keep the host tag as a wrapper. Use th:include when you only want the inner content.
In practice, th:replace is the most commonly used method.