Displaying an iterable of n items in rows of 3 items with thymeleaf?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Displaying an iterable of n items in rows of 3 items with thymeleaf?

balteo
Hi!
Say I have an iterable of n items and I want to display it in a html table in rows of 3 items as follows:

<table>
 <tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
 </tr>
 <tr>
  <td>4</td>
  <td>5</td>
  <td></td>
 </tr>
</table>

This is an example for n=5.

I thought of using the iterStat.count variable and if iterStat.count % 3 ==0 then start a new td but I am not sure how to do that with thymeleaf.

Can anyone please advise?
Regards,
Julien.
Reply | Threaded
Open this post in threaded view
|

Re: Displaying an iterable of n items in rows of 3 items with thymeleaf?

Emanuel
Administrator
If the iterable were an array, then I think you can do this: (I haven't tested the code below, but I hope you get the idea of what it's trying to do)

<table th:if="${yourList.length > 0}">
  <tr th:each="${index: #numbers.sequence(0, yourList.length, 3)}">
    <td th:text="${yourList[index]}"></td>
    <td><div th:if="${yourList[index + 1] != null}" th:text="${yourList[index + 1]}" th:remove="tag"></div></td>
    <td><div th:if="${yourList[index + 2] != null}" th:text="${yourList[index + 2]}" th:remove="tag"></div></td>
  </tr>

If I've understood the numbers.seqence(from, to, step) method correctly, then it will create a list of numbers from 0 to the size of your list, with a gap of 3 between each number, so if you had an array of 10 items, you'd get [0, 3, 6, 9].  That's also what the th:if in the <table> is for: because if your array were empty, you'd get [0], which would cause the loop to iterate, and I'm guessing you don't want that to happen on an empty array?

The next part is to create 3 <td> sections, then just fill them with the values from your array.  I think only the second and third <td>'s need null checks and that inner div, which just gets removed, so you end up with empty <td>'s to fill out the table row.

You can probably do the same with a list by changing .lenth to .size() and [index] to .get(index)
Reply | Threaded
Open this post in threaded view
|

Re: Displaying an iterable of n items in rows of 3 items with thymeleaf?

balteo
thanks Emanuel!