结合百里香的条件和迭代

时间:2016-09-15 11:14:39

标签: thymeleaf

我想使用百日咳和bootstrap生成一个产品列表,以便我连续三个产品。

如果它不是行,我会做类似的事情:

<div class="col-sm-4" th:each="product, : ${products}">
  <div class="product">
    <h3 th:text="${product.name}">Product name</h3>
    <img th:src="${product.imagePath}" />
  </div>
</div>

但我希望将每三种产品都放在<div class="row">中,我无法弄清楚如何做到这一点。还有其他人偶然发现了这个问题吗?如果不在控制器中明确创建三个产品的列表,我怎样才能实现所需的输出?

期望的输出

<div class="row">
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 1 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 2 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 3 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 1 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 2 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
  <div class="col-sm-4">
    <div class="product">
      <h3>Product 3 name</h3>
      <img src="/path/to/image" />
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

我会包含Apache Commons Collections 4.1并使用ListUtils对列表进行分区并迭代如下:

<th:block th:with="partitions=${T(org.apache.commons.collections4.ListUtils).partition(products, 3)}">
  <div class="row" th:each="partition: ${partitions}">
    <div class="col-sm-4" th:each="product: ${partition}">
      <div class="product">
        <h3 th:text="${product.name}">Product name</h3>
        <img th:src="${product.imagePath}" />
      </div>
    </div>
  </div>
</th:block>