Search code examples
htmlfor-loopjinja2nested-loops

Nested For Loop in an html table inside a jinja template


I am trying to refactor this in order to display 1 table with header for headers of the table and value as a corresponding cell value under each header, however, due to the usage of a nested loop I get multiple tables of one col each listed in a vertical order. Any suggestions are appreciated. Thanks.

{% for header in aValueKeys%}
 <table>
  <thead>
    <tr>
     <th>{{ header }}</th>
    </tr>
  </thead>
  <tbody> 
   {% for value in aValues[header] %}
    <tr>
     <td>{{ value }}</td>
    </tr>
  {% endfor %}
  </tbody>
 </table> 
{% endfor %}

values are being used like so:

message = template.render(iD=a_message.iD, aValueKeys=a_message.valueKeys,
                                aValues=a_message.values, aType=a_message.aType,
                                sentence=a_message.sentence)

This renders two tables, however, I need it to be in one table. How do I achieve this although there is a nested loop?


Solution

  • You should surround only blocks that need repeating with a for loop:

    <table>
      <thead>
        <tr>
         {% for header in aValueKeys %}
         <th>{{ header }}</th>
         {% endfor %}
        </tr>
      </thead>
      <tbody> 
        <tr>
         {% for value in aValues %}
         <td>{{ value }}</td>
         {% endfor %}
        </tr>
      </tbody>
    </table>