0

I want to use the index of an thymeleaf-loop as arrayindex inside. Example:

<div th:each="service : ${requestedServices}">
   <div class="col-sm-1">
       <input type="checkbox" th:checked=*{service[index of loop?].requested}">
   </div>
</div>

I'll already tried to use serviceStat.index inside the array

${requestedServices} is an ArrayList of Requested Service

class RequestedService {
   Service service
   boolean requested
}
class Service {
   String name;
   int value;
}

I hope to find an answer for my problem

Ti1991
  • 1
  • 1
  • Does this answer your question? [Thymeleaf - How to loop a list by index](https://stackoverflow.com/questions/38367339/thymeleaf-how-to-loop-a-list-by-index) – seenukarthi Apr 05 '22 at 08:44

1 Answers1

0

serviceStat.index is the correct way to to index into your array (see the last paragraph of keeping iteration status -- If you don’t explicitly set a status variable, Thymeleaf will always create one for you by suffixing Stat to the name of the iteration variable:).

That being said, because you are using it in a th:field attribute, you must use preprocessing for your index.

<div th:each="service : ${requestedServices}">
   <div class="col-sm-1">
       <input type="checkbox" th:checked="*{service[__${serviceStat.index}_].requested}" />
   </div>
</div>

(You might also be interested in the Thymeleaf tutorial on dynamic fields.)

Metroids
  • 18,999
  • 4
  • 41
  • 52