Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 List of Dictionaries into HTML Table?

So im trying to create an HTML table using Jinja2 from a list of dictionaries (as returned by a Flask SQL select statement).

Right now test_list has stored a list of dictionaries (with the key's being the DB columns).

Right now im using this:

<table style="width:100%">
   {% for dict_item in history_list %}
   {% for key, value in dict_item.items() %}
    <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
    </tr>
   {% endfor %}
{% endfor %}
</table>

It does work, but it's basically producing 2 columns (one being the keys and one being the columns). Im wanting to get the DB keys as columns titles in the table and then just the values placed into each column.

Is this possible? since I would want to iterate through the key's just once?

like image 787
msmith1114 Avatar asked Jan 04 '23 08:01

msmith1114


1 Answers

You need something like this, that provides a header row of th elements, then proceedes to the data rows (the body of the table).

<table style="width:100%">
  <!-- table header -->
  {% if history_list %}
  <tr>
     {% for key in history_list[0] %}
     <th> {{ key }} </th>
     {% endfor %}
  </tr>
  {% endif %}

  <!-- table rows -->
  {% for dict_item in history_list %}
  <tr>
     {% for value in dict_item.values() %}
     <td> {{ value }} </td>
     {% endfor %}
  </tr>
  {% endfor %}
</table>
like image 147
Jonathan Eunice Avatar answered Jan 06 '23 21:01

Jonathan Eunice