所以我尝试使用 Jinja2 从字典列表(由 Flask SQL 选择语句返回)中创建一个 HTML 表。
现在 test_list 已经存储了一个字典列表(键是数据库列)。
现在我正在使用这个:
<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>
它确实有效,但它基本上生成 2 列(一列是键,一列是列)。我想获取数据库键作为表中的列标题,然后只是将值放入每一列。
这可能吗?因为我只想遍历 key 一次?
最佳答案
您需要类似这样的东西,它提供了 th
元素的标题行,然后继续到数据行(表的主体)。
<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>
关于python - Jinja2 字典列表到 HTML 表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847877/