【问题标题】:Duplicated thymeleaf fragment after each loop每个循环后重复的百里香片段
【发布时间】:2017-12-04 04:20:50
【问题描述】:

我有一个应该呈现地图内容的 Thymeleaf 模板。这是模板:

<div class="akuiteo list-group" data-th-each="akuiteo:${akuiteoMap.akuiteoMap}">
    <div data-th-replace="akuiteo::akuiteoView(${akuiteo.value},${akuiteo.key})"></div>
</div>

在 akuiteoView 我有:

<button data-th-fragment="akuiteoView(commits,akuiteoNr)" class="akuiteo-file" data-th-each="commit:${commits}" data-th-id="${akuiteoNr}">
    <p data-th-text="${akuiteoNr}"></p>
    <div data-th-replace="commitDetails::commitView(${commit})">replace me</div>
</button>

我得到的输出是:

<body>
    <div class="akuiteo list-group">
         <button> content </button>
    </div>
    <div class="akuiteo list-group">
         <button> content </button>
         <button> content </button>
         <button> content </button>
         <button> content </button>
         <button> content </button>
         <button> content </button>
    </div>
</body>

akuiteo 类的 div 重复了,而且每次提交都有一个按钮,而不是每个 akuiteo 实例有一个按钮,我不明白为什么会发生这种情况,预期的输出是:

<body>
    <div class="akuiteo list-group">
         <button> content(a list of one commit) </button>
         <button> content(a list of 6 commits) </button>
    </div>
</body>

【问题讨论】:

  • 在我发布答案之前,您能告诉我为什么要使用&lt;button&gt; 元素来呈现内容吗?你不应该在按钮中嵌套像&lt;div&gt;&lt;p&gt;这样的标签,因为它在语法上不正确,所以你的按钮应该替换为div
  • 我这样做是因为它有一个引导功能,可以使用按钮启用多选列表,尽管有可能避免这种情况

标签: spring html thymeleaf


【解决方案1】:

这是因为data-th-each。 Thymeleaf 迭代您的地图条目并为每个条目创建单独的div。然后按钮也会发生同样的事情:thymeleaf 为每次提交渲染一个新的。您应该查看解释 iterating using th:each 的文档。

要获得预期的输出(1 个 div 和 2 个按钮),您应该重新设计您的页面,例如像这样:

<div class="akuiteo list-group">
    <button data-th-each="akuiteo:${akuiteoMap.akuiteoMap}">
        <span data-th-replace="akuiteo::akuiteoView(${akuiteo.value},${akuiteo.key})"></span>
    </button>
</div>

和:

<span data-th-fragment="akuiteoView(commits,akuiteoNr)" data-th-each="commit:${commits}">
    <!-- here goes content of a single commit -->
<span>

顺便说一句,&lt;button&gt; 标签不应该包含像&lt;div&gt;&lt;p&gt; 这样的元素。我对提交的内容一无所知,但考虑将&lt;button&gt; 重新设计为&lt;div&gt;(以保留包含&lt;p&gt;&lt;div&gt; 的提交结构),或者以文本形式总结来自akuiteo 的提交(保留&lt;button&gt;)。

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 2014-01-05
    • 2012-09-21
    • 2020-11-28
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多