Search code examples
springspring-bootbootstrap-4thymeleaf

Thymeleaf iterate list with alternate colors


In my Spring Boot project, I am iterating a Thymeleaf list like below:

<div th:each="filename: ${files}">
<div class="bold badge badge-primary" th:text="${filename}"></div>
</div>

Question: I am clueless on how can assign badge-primary and badge-secondary (bootstrap4.5) classes to alternate list items while iterating through them?

In simple words, first list item should have badge-primary class, second list item badge-secondary and so on.

Is it possible? If yes, then how? Thanks.


Solution

  • When using th:each, Thymeleaf offers a mechanism useful for keeping track of the status of your iteration: the status variable. Per Thymeleaf documentation example, your code may look like the following ...

    <div th:each="filename,iterStat: ${files}">
        <div class="bold badge badge-primary" th:class="'bold badge'" th:classappend="${iterStat.odd}? 'badge-primary' : 'badge-secondary'" th:text="${filename}"></div>
    </div>