繁体   English   中英

Jinja2 字典列表到 HTML 表?

[英]Jinja2 List of Dictionaries into HTML Table?

所以我试图从字典列表中使用 Jinja2 创建一个 HTML 表(由 Flask SQL select 语句返回)。

现在 test_list 已经存储了一个字典列表(键是 DB 列)。

现在我正在使用这个:

<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 列(一列是键,一列是列)。 我想将 DB 键作为表中的列标题,然后将值放入每列。

这可能吗? 因为我只想遍历密钥一次?

你需要这样的事情,它提供的标题行th元素,然后proceedes的数据行(表体)。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM