首页 > 解决方案 > Thymeleaf 条件添加标签

问题描述

我的请求属性(“items”)中有一个项目列表,该列表将由引导程序 4(https://getbootstrap.com/docs/4.2/components/card/#card-decks)卡组 3 个项目呈现每行。我可以通过使用 JSTL 来做到这一点

<c:forEach var="item" items="${items}" varStatus="status">
    <c:if test="${status.index%3 == 0}"> <!--Start new row-->
        <c:if test="${status.index > 0}"> <!--Close the previous deck-->
            </div>
        </c:if>
        <div class="card-deck mt-3"> <!--Create new deck-->
     </c:if>
     <div class="card bg-light">
         <h5 class="card-header">${item.id}</h5>
         <div class="card-body"></div>
     </div>  
</c:forEach>

现在,我如何使用 Thymeleaf 实现相同的目标?谢谢

标签: servletsbootstrap-4thymeleaf

解决方案


您的代码会将 Thymeleaf 转换为类似于以下代码的内容。

<th:block th:each="item, stat: ${items}">
    <th:block th:if="${stat.index eq 0}">
        <th:block th:if="${stat.index &gt; 0}">
            </div>
        </th:block>
        <div class="card-deck mt-3"> <!--Create new deck-->
    </th:block>
    <div class="card bg-light">
         <h5 class="card-header" th:text="${item.id}"></h5>
         <div class="card-body"></div>
     </div>  
</th:block>

推荐阅读