0

My problem is with using thymeleaf iteration and if-else condition together. Suppose i have 100 products in my mysql database i want to show them on a webpage using cards and there are only 4 cards in a row(I am able to print them in a row), but i want to change the row after every 4 iteration(0-3),so that new four cards will be shown in next row.

My thymeleaf Template Page:-

<div class="container" >
<div class="row">
    <div class="col-xl-3" th:each="products : ${ListOfProducts}">
        <div class="card" style="width: 15rem;">
            <img class="card-img-top" src="..." alt="Card image cap">
            <div class="card-body">
                <p class="card-title" th:text = "${products.productName}"></p>
                <hr>
                <p class="card-text" th:text = "${products.productCost}"></p>
                <a href="#" class="btn btn-primary">AddToCard</a>
            </div>
        </div>
     </div>
</div>

I know we can do it using loops and if-condition but i am new to thymeleaf syntax, so please help me to get out of this rid. Thanks in advance,Your words are value for me.

Atharva
  • 87
  • 1
  • 9
  • I think you would be better off using a [CSS grid layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout) for this, since this is a page layout issue more than a list processing issue. With a grid, you can define the number of cells per row in different ways - for example `grid-template-columns: 200px 200px 200px 200px;` for a grid containing 4 cells per row. Now your Thymeleaf iterator does not need to know anything about the "4 cards in a row" requirement. – andrewJames Aug 16 '20 at 14:13
  • Alternatively, I would structure the data in Java to match your requirement before passing the data to Thymeleaf. For a somewhat related example, take a look at [this question](https://stackoverflow.com/questions/61111220/thyemleaf-nested-iteration-triggers-org-thymeleaf-exceptions-templateinputexcept). By doing this, you would also end up with Thymeleaf iterators which do not rely on any special counting or modulo logic. – andrewJames Aug 16 '20 at 14:52
  • Alternative to the alternative, you can use the partition function from apache commons. See this: https://stackoverflow.com/a/39515137/4126893 – Metroids Aug 16 '20 at 15:49
  • @Metroids i google it but unable to understand what is apache comman collection can you please suggest me some resourses to learn about. Thanks your help. – Atharva Aug 16 '20 at 15:54
  • Hmm... it's just a collection of utilities. You can just include it in your pom file, and then use the methods in it. here's the [documentation for partition](https://commons.apache.org/proper/commons-collections/javadocs/api-4.4/org/apache/commons/collections4/ListUtils.html#partition-java.util.List-int-). – Metroids Aug 16 '20 at 16:20
  • Can i use this in a project which i am creating to include in resume – Atharva Aug 16 '20 at 16:28

0 Answers0