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

如何在Thymeleaf中向带参数片段传入另一个带参数片段?

Thymeleaf嵌套片段无法正确解析的问题解决

我在Thymeleaf模板中定义了两个片段:

<p th:fragment="paragraph(text)" style="padding: 20px; background: #eee;">[(${text})]</p>

<a th:fragment="link(href, text)" th:href="${href}">[[${text}]]</a>

单独使用这些片段时一切正常:

<p th:replace="~{ :: paragraph('Click here to get beauty: ')}" />

<a th:replace="~{ :: link('#', 'beauty ahead')}" />

但尝试将link片段传入paragraph片段时,并未按预期工作:

<!-- 未按预期工作 -->
<p th:replace="~{ :: paragraph(~{ :: link('#', 'beauty ahead')})}" />

生成的HTML源码如下,可以看到link片段虽被插入,但未被正确处理:

<p style="padding: 20px; background: #eee;">
    <a th:fragment="link(href, text)" th:href="${href}">
        <th:blockth:text="${text}"></th:block>
    </a>
</p>

尝试解决方案与报错

针对提供的解决方案,我修改了代码并放在同一文件中测试:

<a th:fragment="link(href, text)" th:href="${href}">[[${text}]]</a>

<p th:fragment="paragraph(content)" style="color: red">
    <th:block th:replace="${content}"></th:block>
</p>

<p th:replace="~{ :: paragraph(~{ :: my-link}, '')}">
    <a th:ref="my-link" th:replace="~{:: link('#', 'beauty ahead')}"></a>
</p>

调整了片段引用路径并闭合了标签,但抛出了以下错误:

org.thymeleaf.exceptions.TemplateInputException: Error resolving fragment: "${content}": template or fragment could not be resolved

最终成功方案

将片段与调用代码拆分到不同文件后,问题解决:

fragments.html

<!-- 片段不能与替换操作位于同一文件中 -->
<a th:fragment="link(href, text)" th:href="${href}">[[${text}]]</a>

<p th:fragment="paragraph(content)" style="color: red">
    <th:block th:replace="${content}"></th:block>
</p>

layout.html

<p th:replace="~{fragments :: paragraph(~{ :: my-link})}">
    <a th:ref="my-link" th:replace="~{fragments :: link('#', 'beauty ahead')}"></a>
</p>

非常感谢RoToRa的解释与代码!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:33:12