Search code examples
javaspringthymeleaf

Thymeleaf: th:each for two table rows?


How can I, inside a th:each loop create a group of two rows instead of just one?

I know I can do:

<tr th:each="obj: ${listOfObjects}">
   <td>a column with data: ${obj.id}</td>
</tr>

However, I want two <tr> elements to be created, as I would do with JSTL:

<c:forEach items="${listOfObjects}" var="obj">
    <tr>
       <td>${obj.id}</td>
    </tr>
    <tr>
       <td>${obj.name}</td>
    </tr>
</c:forEach>

Is there a way to achieve that with Thymeleaf?


Solution

  • You could use a th:block element for grouping the rows together and repeat them:

    <th:block th:each="obj: ${listOfObjects}">
        <tr>
           <td th:text="${obj.id}"></td>
        </tr>
        <tr>
           <td th:text="${obj.name}"></td>
        </tr>
    </th:block>
    

    You can read more about th:block here