Nested th:each

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

Nested th:each

    }
    }

I haven't tested this, but I assume the logic is correct.

My question is, how to do this with the th:each attribute???
I tired using conditional expressions, iteration status variables etc. But nothing worked.
iteration status variables help to keep track of the index, but i don't how to force a loop to start with custom iteration index.

Pls let me know the solution for this.

Thanks!
kp
kp
Here is my requirement, I have a list of objects which I have to display in a grid with 4 objects per row.

something like this:
 obj1 obj2 obj3 obj4
 obj5 obj6 obj7 obj8
 .
 .
 obj13 obj14 obj 15 obj16

So nested loops is an obvious solution here in which, inner loop's index depends on the outer loop.
Here's the pseudo code:
 for(int i=0; i<size/4 ; i+=4)
 {
   <tr>
   for(int j=i ; j<(i+4) ; j++) //NOTICE: The inner loop index gets initialized with the outer loop index
   {
     
obj
LNC
Reply | Threaded
Open this post in threaded view
|

Re: Nested th:each

LNC
I am having the same issue too.  The inner index does not seem to reset at the start of each outer loop.
Reply | Threaded
Open this post in threaded view
|

Re: Nested th:each

Emanuel
Administrator
This post was updated on .
In reply to this post by kp
EDIT: I initially posted a long answer, but just thought of a better way that's closer to your pseudo code example:

---
You can use the #numbers.sequence() utility method to create value ranges to loop through like in your psuedo code:

<p th:each="i: ${#numbers.sequence(0, (list.size() / 4) - 1)}">
  <span th:each="j: ${#numbers.sequence(i * 4, i * 4 + 3)}" th:if="${list.size() gt j}" th:text="${list.get(j)} + ', '"></span>
</p>

The th:if is just to make sure you don't get ArrayIndexOutOfBoundsException.
kp
Reply | Threaded
Open this post in threaded view
|

Re: Nested th:each

kp
Thanks Emanuel!!
I never thought of this.. I will try this. Thanks again!
kp
Reply | Threaded
Open this post in threaded view
|

Re: Nested th:each

danielfernandez
Administrator
In reply to this post by Emanuel
Well done, Emanuel.

I've just added this to the TODO list for 2.0.9: https://github.com/thymeleaf/thymeleaf/issues/27
A #numbers.sequence(...) method that allows the specification of a "step" argument would have been useful here.

Thanks,
Daniel.
Reply | Threaded
Open this post in threaded view
|

Re: Nested th:each

aquariusm
In reply to this post by Emanuel
It's great answer, i resolved the question on a paging problem with the answer。Thanks very much!