Thymeleaf中th:insert失效但th:replace正常工作的原因排查
th:insert Fails but th:replace Works in Spring Boot 1.4.2 + Thymeleaf Great question—this issue comes down to a critical version difference between Thymeleaf 2.x and 3.x, and which documentation you’re referencing. Let’s break it down step by step.
Key Background: Version Mapping
Spring Boot 1.4.2.RELEASE ships with Thymeleaf 2.1.5.RELEASE by default. The behavior you described (where th:insert inserts fragment content into a <div> and th:replace replaces the <div>) is actually the definition for Thymeleaf 3.0+, not the 2.x version you’re using.
Thymeleaf 2.x vs. 3.x: Include Directive Behavior
Let’s clarify what each directive does in your current version (2.x):
th:replace: This fully replaces the target element (your<div>) with the entire fragment element (your<nav th:fragment="navbar">). This matches what you’re seeing work correctly.th:insert: This inserts the entire fragment element (including the<nav>tag) as a child of your target<div>. It doesn’t strip the fragment’s root element—so you’d end up with<div><nav>...</nav></div>instead of just the nav content inside the div. If your CSS or layout expects the nav to replace the div (or not be nested), this might look like it’s "failing" when it’s actually working as designed for 2.x.th:include: This is the 2.x equivalent of what you expectedth:insertto do—it inserts only the content of the fragment (excluding the<nav>root tag) into your target<div>.
Why You’re Seeing the "Failure"
You’re likely referencing Thymeleaf 3.x documentation, which redefined these directives:
- In 3.x,
th:insertinserts the fragment content into the target element (stripping the fragment’s root tag if needed) th:replacereplaces the target element with the fragmentth:includewas deprecated in 3.x
Fixes for Your Use Case
Use
th:includeinstead ofth:insert(for Thymeleaf 2.x):<th:include="fragments/navbar :: navbar"></th:include>This will insert just the nav content into your
<div>as you expected.Upgrade to Thymeleaf 3.x:
If you want to use the 3.x behavior, you can either:- Upgrade your Spring Boot version to 1.5.x or higher (Spring Boot 1.5+ defaults to Thymeleaf 3.x)
- Manually override the Thymeleaf version in your
pom.xml:<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>3.0.15.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.4.RELEASE</version> </dependency>
Once upgraded, your original
th:insertwill behave as described in the 3.x docs.
内容的提问来源于stack exchange,提问作者not a Programmer

