【问题标题】:Using variables to build fragment name in th:include - ThymeLeaf + Spring Boot使用变量在 th:include 中构建片段名称 - ThymeLeaf + Spring Boot
【发布时间】:2016-04-06 14:22:53
【问题描述】:

我想在没有th:fragment 的情况下使用fragment 功能(仅使用id)。在我的代码中,要包含的目标片段是从迭代器动态构建的。问题是为要正确呈现的th:include 创建正确的表达式。我已经按照教程尝试了连接、预处理和文字替换,但没有结果——让我想——th:include 允许这样做吗?

片段定义(它在我的模板下名为Comments.html 的文件中,与我的其他模板一起)。

<div id="LOW_SCORE_COMMENT">

是这样称呼的

<div class="well" th:each="commentFragment : ${allComments}">
    <div th:include="'Comments :: #' + {__${commentFragment}__}">
    </div>          
</div>

allCommentsIterator&lt;String&gt;,检索到的字符串是片段 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>

基本上把allcomments改成TreeMap来解决排序问题,但现在报错如下:

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

【问题讨论】:

  • 看来你误用了th:include。来自关于th:include 的文档:语句的第一部分是我们引用的模板名称。双冒号后的表达式是片段选择​​器(片段名称或 DOM 选择器)。但在你的代码中,这一切都混在一起了。
  • 如果如上所述,我的片段是&lt;div id="LOW_SCORE_COMMENT"&gt; 并且${commentFragment} 解析为LOW_SCORE_COMMENT,它不应该读作th:include= "Comments :: #LOW_SCORE_COMMENT" 。你能解释一下你的意思是混淆吗?我指的是使用 Thymeleaf 指南第 8 节引用没有 th:fragment 的片段

标签: spring-boot thymeleaf


【解决方案1】:

问题在于缺少预处理符号__ - 请参阅Thymeleaf documentation。没有__ 的表达式将按原样替换并传递给生成的 HTML 页面。

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

预处理后的表达式与普通表达式完全一样,但由双下划线符号包围(如__${expression}__)。

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

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

【讨论】:

    【解决方案2】:

    这应该使用片段表达式,如 here 解释的那样

    <div class="well" th:each="commentFragment : ${allComments}">
      <div th:include="~{Comments :: #__${commentFragment}__}">
      </div>          
     </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2020-01-25
      相关资源
      最近更新 更多