Combining conditions and iterations in thymeleaf

2020-05-01 21:47发布

I want to generate a list o products using thymeleaf and bootstrap so that I have three products on a row.

If it weren't for the rows, I would have done something like:

<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>

But I want to enclose each three products in a <div class="row"> and I just can't figure out how to do this. Has anyone else stumbled upon this problem ? How can I achieve the desired output without explicitly creating lists of three products in the controller ?

Desired output

<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>

标签: thymeleaf
1条回答
乱世女痞
2楼-- · 2020-05-01 22:11

I would include Apache Commons Collections 4.1 and use ListUtils to partition the list and iterate like this:

<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>
查看更多
登录 后发表回答