Colleagues, good afternoon.

There is a site with an example https://www.baeldung.com/thymeleaf-list

And I do not understand the place where they write

However, it is also possible to use the itemstat variable to define it.

If so there is an iteration

<tr th:each="book, itemStat : *{books}"> 

why can't we use

 th:field="*{book.title}" 

instead

 th:field="*{books[__${itemStat.index}__].title}" 

Tell me please.

  • Read the documentation . There it’s more clearly described what itemStat is - not a Programmer
  • @notaProgrammer, comment in no where. Of course I read and I understand what is written there. Therefore, I ask about this case. After all, that book.title (where itemStat.index = 0), even though books [ $ {itemStat.index} ] .title, which will be equal to books [0] .title, is the same. - Dred
  • And you have seen that in addition to the index variable there is also first, last, even, odd (which may be needed in order to, say, add some kind of css class for paired, not paired elements, it is possible to select somehow the first element or you just want to show only paired elements) - not a Programmer
  • Dear @notaProgrammer. The question was asked not Why the index in itemStat, but why it was impossible to use it in this case? - Dred
  • And if just book.title without * {}? - not a Programmer

2 answers 2

You can not use itemStat .

An example is made to demonstrate how to get the index of an element.

To get the index, you need to use the itemStat variable, and outputting an item through the index is just a demonstration of the use of this index.

  • Good day. So you can use it like this? th: field = "* {book.title}" or th: field = "* {books [ $ {itemStat.index} ] .title}" or so th: field = "$ books [0] .title"? - Dred

In general, I did some test. It turns out that for different situations either you need to use iterStat, or not. Depends on whether the list, Map, Object or something else was transferred.

In this case, the object passed to th: object = "$ {selectedProduct}" is an object that contains only a List <> mapList;

 th:field="*{product.productId}" th:field="*{mapList[__${iterStat.index}__].productId}" th:field="${mapList[__${iterStat.index}__].productId}" th:field="${__${product.productId}__}" th:field="${product.productId}" th:field="${product.productId != null} ? ${product.productId} : ${product.enumName}" th:value="*{product.productId}" th:value="${mapList[__${iterStat.index}__].productId}" th:value="*{mapList[__${iterStat.index}__].productId}" th:value="${__#{product.productId}__}" th:value="${product.productId}" th:value="${product.customName != null} ? ${product.productId} : ${product.enumName}" 

For me, it was appropriate for the form to display the value, but it could not be changed, this is the option

  <input readonly type="text" th:field="*{mapList[__${iterStat.index}__].productId}"/>