【问题标题】:Thymeleaf: Delete the div that contains iterating attribute (th:each) after looping through or conditional attribute (th:if) after evaluatingThymeleaf:循环后删除包含迭代属性(th:each)或评估后包含条件属性(th:if)的div
【发布时间】:2020-04-25 09:24:22
【问题描述】:

在 Thymeleaf 中,是否可以 delete wrapper div 包含条件循环?假设以下代码在 SpringBoot 应用程序中,我打算在评估条件并遍历错误列表后擦除第一个和第二个 div。

<div th:if="${errors != null}">
    <div th:each="error : ${errors}">
        <div th:utext="${error}"></div>
    </div>
</div>

我想在不使用 JavaScript 的情况下实现这一点。

【问题讨论】:

    标签: html spring-boot thymeleaf


    【解决方案1】:

    您也可以使用&lt;th:block /&gt;(未渲染)。此外,无需将迭代和文本分开。您应该能够像这样生成相同的代码:

    <th:block th:if="${errors != null}">
        <div th:each="error : ${errors}" th:utext="${error}" />
    </th:block>
    

    (比起th:remove="tag",我更喜欢&lt;th:block /&gt;。)

    【讨论】:

    • 非常有趣,'th:block' 比 'th:remove="tag"' 有什么优势
    • +1 赞成迭代的简化版,但是你不觉得普通版更易读吗(普通版很像 java 循环)
    • IMO,th:remove 更多地用于自然模板而不是实际的模板功能...我认为模板应尽可能匹配 html(看到 3 个嵌套的 div 会令人困惑s,当输出没有嵌套的divs)。至于java循环......我只是觉得这样更具可读性。
    【解决方案2】:

    只需将th:remove="tag" 属性添加到所需的div 即可删除包装器div。

    <div th:if="${errors != null}" th:remove="tag">
        <div th:each="error : ${errors}" th:remove="tag">
            <div th:utext="${error}"></div>
        </div>
    </div>
    

    上述代码的结果将是:

    <div>Error 1</div>
    <div>Error 2</div>
    <div>Error 3</div>
    <div>Error 4</div>
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      相关资源
      最近更新 更多