在 th:include 中使用变量构建片段名称 - ThymeLeaf + Spring Boot

aaa*_*hhh 3 thymeleaf spring-boot

我想使用fragment不带th:fragment(仅使用 id)的功能。在我的代码中,要包含的目标片段是从迭代器动态构建的。问题是创建正确的表达式以th:include正确渲染。我已经按照教程尝试了连接、预处理和文字替换,但没有结果 - 让我思考 - 这是否允许th:include

片段定义(它位于我的模板下调用的文件中Comments.html,以及我的其他模板)。

<div id="LOW_SCORE_COMMENT">
Run Code Online (Sandbox Code Playgroud)

它被这样称呼

<div class="well" th:each="commentFragment : ${allComments}">
    <div th:include="'Comments :: #' + {__${commentFragment}__}">
    </div>          
</div>
Run Code Online (Sandbox Code Playgroud)

allComments是一个Iterator<String>,并且检索到的字符串是片段 id,因此它应该构建整个页面。但我收到这个错误

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "'Comments", template might not exist or might not be accessible by any of the configured Template Resolvers

请注意错误消息中 " 和 Comments 之间的单引号。

你有什么建议吗?

编辑:我尝试了这段代码

<div class="well" th:each="commentFragment,iterstat : ${allComments}"> <div th:include="${commentFragment.getValue()}"></div>

本质上改为allcommentsaTreeMap来解决排序问题,但现在错误如下:

org.thymeleaf.exceptions.TemplateInputException:解析模板“Comments :: #LOW_SCORE_COMMENT”时出错,模板可能不存在或可能无法被任何配置的模板解析器访问

aaa*_*hhh 5

问题在于缺少预处理符号__- 请参阅Thymeleaf 文档。表达式 without__只是按原样替换并传递到生成的 HTML 页面。

预处理是在正常表达式之前执行表达式,允许修改最终将执行的表达式。

预处理的表达式与普通表达式完全相同,但显示为双下划线符号(如__${expression}__)。

正确的工作代码是这样的:

<div class="well" th:each="commentFragment : ${allComments}">
    <div th:include="__${commentFragment.getValue()}__"></div>
Run Code Online (Sandbox Code Playgroud)