14

I am new to thymeleaf and am converting all my jsp code to thymeleaf.I don't know how to convert this below code to thymeleaf.Do anyone know how to convert the below code to thymeleaf?

<logic:iterate id="id" property="idList" name="sampleForm" indexId="i">
    <label for="id<%=i%>">
      <bean:write name="id" property="id" />
    </label>
</logic:iterate>

Please tell me how to initialize the index value in thymeleaf to be used in some values??

2 Answers 2

20
<label th:each="id,status : ${idList}" th:for="|id${status.index}|" th:text="${id.id}"></label>
  • th:each will iterate over the idList, assign each item to id and create a label for each item. The status of the item can be assigned by adding an extra name, separated by a comma (status in this example).
  • th:for will set the for attribute of the label. The pipes (|) are used for easy string concatenation.
  • th:text will set the inner text of the label to the ID.
0
1

You can also use it like this:

<label th:each="id : ${idList}" th:for="${'id' + idStat.index}" th:text="{id.id}">

This starts the index from 0

If you want to start the index from 1 use this

<label th:each="id : ${idList}" th:for="${'id' + idStat.count}" th:text="{id.id}">

Check out the Thymeleaf documentation

Not the answer you're looking for? Browse other questions tagged or ask your own question.