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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With