Building Tables Ddynamically with th:each Based On th:if Condition

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

Building Tables Ddynamically with th:each Based On th:if Condition

alexmsenger
Hi!

I've been trying all sorts of different things by now and I just can't seem to get anywhere. What I'm trying to do is to dynamically create a table of the sort:

<table>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
  <!-- ... -->
</table>

In order to achieve this, here's what I'm thinking:

<table>
  <tr>
    <th:block th:each="foo,iterStat : ${#numbers.sequence(1,some_numeric_var)}">
      <td>
        [[${foo}]]
      </td>
      
      <th:block th:if="${iterStat.count} % 2 == 0">
        </tr><tr> 
      </th:block>
    </th:block>
  </tr>
</table>

But instead what I'm getting is this:

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

Can someone point me to what I'm doing wrong and why? And how I could achieve my goal? Thank you!

Best
Alex
Reply | Threaded
Open this post in threaded view
|

Re: Building Tables Ddynamically with th:each Based On th:if Condition

Metroids
<table>
  <tr th:each="i: ${#numbers.sequence(0,1)}">
    <td th:each="j: ${#numbers.sequence(0,1)}" th:text="${i * 2 + j + 1}" />
  </tr>
</table>
Reply | Threaded
Open this post in threaded view
|

Re: Building Tables Ddynamically with th:each Based On th:if Condition

Metroids
Oh, as for what you're doing wrong.  You can't create tags in the middle (like you're trying to do with the
<tr>
 in the second th:block).  It should be valid html, and when you look at it without the thymeleaf you're looking at this:

<table>
  <tr>
    <td></td>
    </tr><tr> 
  </tr>
</table>

Which would never work.

Reply | Threaded
Open this post in threaded view
|

Re: Building Tables Ddynamically with th:each Based On th:if Condition

alexmsenger
Thanks for the Info! I've updated my code and included the nested loop. I might need small tweaks in the future but for now it's actually quite beautiful. I actually didn't know that the code without the thymeleaf should also make for valid HTML. Every day something new :-)

I don't know if it's possible to mark something as resolved here or mark a question as "correct answer" but consider it so. :-)