Home > Back-end >  How to place iteration index into array index using thymeleaf?
How to place iteration index into array index using thymeleaf?

Time:04-12

I am trying to iterate over list with keeping track of iteration and I want to place iteration index into array index of that list:

What I tried:

<tr th:each="experience, iter : *{experiences}">
    <td>Experience name:</td>
    <td><input type="text" th:field="*{experiences[iter.index]}" value="${experience.name}">
</tr>

Here I get NumberFormatException. So I tried to use $, because I think that iter is a variable:

<tr th:each="experience, iter : *{experiences}">
    <td>Experience name:</td>
    <td><input type="text" th:field="*{experiences[${iter.index}]}" value="${experience.name}">
</tr>

Here, ${iter.index} is not evaluated, so I get error that ${iter.index} is not a number (again NumberFormatException).

CodePudding user response:

You can use the iter.index using 2 underscores.

<tr th:each="experience, iter : *{experiences}">
    <td>Experience name:</td>
    <td><input type="text" th:field="*{experiences[__${iter.index}__]}" />
</tr>

__${...}__ syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression. https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf#preprocessing

  • Related