Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate with index using thymeleaf

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??

like image 768
Deepak Ramakrishnan Kalidass Avatar asked Jan 06 '14 07:01

Deepak Ramakrishnan Kalidass


People also ask

How do you break the loop in Thymeleaf?

The best solution would be the put this logic in the controller and put the first product of type 'T' in a separate attribute. If that's not possible, another solution would be to write a Thymeleaf extension (or if using Spring a bean) that does this.


2 Answers

<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.
like image 197
Tom Verelst Avatar answered Oct 10 '22 02:10

Tom Verelst


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

like image 34
haschibaschi Avatar answered Oct 10 '22 03:10

haschibaschi