André Ribeiro
André Ribeiro

Reputation: 79

Thymeleaf get the previous object by index

How can I get the previous object by index (e.g. iterStat-1)?

This code is based on the thymeleaf tutorial example.

<table>
    <tr>
        <th>NAME</th>
        <th>PRICE</th>
        <th>IN STOCK</th>
    </tr>
    <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
</table>

I want something like the following.

<td th:text="${prod[iterStat-1].price}"></td>

Upvotes: 0

Views: 1544

Answers (1)

Jakub Ch.
Jakub Ch.

Reputation: 3727

You can achieve that with

<td th:unless="${iterStat.first}" th:text="${prods[iterStat.index-1].price}"></td>

th:unless="${iterStat.first}" will not render cell for the first element, so that you don't try to obtain element of index -1 (would results in exception).

Upvotes: 2

Related Questions