Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf Loop Until a Number

I make a search and get response from server with Thymeleaf. This holds the number of results:

${response.count}

I want to make an iteration like that:

for (int i = 1; i <= response.count; i++) {
    if (response.page == i) {
        <button class="active">Dummy</button>
    } else {
        <button>Dummy</button>
    }
}

How can I do that? I've tried something like that:

${#numbers.sequence(0, response.count)}

but didn't work.

EDIT: I've tried that but didn't work too:

<button th:each="i: ${#numbers.sequence(0, response.count - 1)}" th:class="${i == response.page} ?: active">Dummy</button>
like image 806
kamaci Avatar asked Oct 12 '16 19:10

kamaci


People also ask

How do you break the loop in Thymeleaf?

The best solution would be the put this logic in the controller and put the first product of type 'T' in a separate attribute. If that's not possible, another solution would be to write a Thymeleaf extension (or if using Spring a bean) that does this.

How do I add if condition in Thymeleaf?

In some situations, you want a certain snippet of the Thymeleaf Template to appear in the result if a certain condition is evaluated as true. To do this you can use the attribute th:if. Note: In Thymeleaf, A variable or an expression is evaluated as false if its value is null, false, 0, "false", "off", "no".


1 Answers

This works for me:

<th:block th:each="i: ${#numbers.sequence(0, response.count - 1)}">
    <button th:if="${response.page == i}" class="active">Dummy</button>
    <button th:unless="${response.page == i}">Dummy</button>
</th:block>
like image 162
Metroids Avatar answered Sep 18 '22 17:09

Metroids