You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf运行报错Error resolving fragment: ${h3} 无法解析模板片段求助

错误原因

  • 你使用的~{::h3}、~{::h4}是Thymeleaf的DOM选择器片段表达式,默认会在当前模板的已解析静态DOM结构中查找匹配元素。
  • 你把h3、h4写在了带有th:replace属性的div内部,而th:replace的执行逻辑是直接用目标片段替换当前整个div元素,当前div内部的子内容在解析片段参数时不会被纳入DOM查找范围,导致你传递的h3、h4参数实际为空,最终抛出找不到对应片段的异常。

解决方法

把需要传递的h3、h4元素移到th:replace所在div的外部,保证DOM选择器可以正常匹配到对应元素,修改后的代码参考如下:

<td>
    <div th:fragment="copy(h3,h4)">
        &copy; 2011 The Good Thymes Virtual Grocery
        <div th:replace="${h3}">洛阳</div>
        <div>copy</div>
        <div th:replace="${h4}">月明</div>
    </div>
    <!-- 把h3、h4移到replace标签外部 -->
    <h3 class="one">你好</h3>
    <h4 class="two">号码</h4>
    <div th:replace="this::copy(~{::h3},~{::h4})">
        <h2>梦里寻欢;</h2>
    </div>
</td>

如果你不想把h3、h4暴露在外部,也可以改用Thymeleaf 3.0+支持的内联片段传递语法,直接在参数位置定义要传递的片段内容:

<td>
    <div th:fragment="copy(h3,h4)">
        &copy; 2011 The Good Thymes Virtual Grocery
        <div th:replace="${h3}">洛阳</div>
        <div>copy</div>
        <div th:replace="${h4}">月明</div>
    </div>
    <div th:replace="this::copy(~{<h3 class='one'>你好</h3>},~{<h4 class='two'>号码</h4>})">
        <h2>梦里寻欢;</h2>
    </div>
</td>

内容的提问来源于stack exchange,提问作者user14124587

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:36:03