简体   繁体   English

Jinja2 字典列表到 HTML 表?

[英]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).所以我试图从字典列表中使用 Jinja2 创建一个 HTML 表(由 Flask SQL select 语句返回)。

Right now test_list has stored a list of dictionaries (with the key's being the DB columns).现在 test_list 已经存储了一个字典列表(键是 DB 列)。

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).它确实有效,但它基本上产生 2 列(一列是键,一列是列)。 Im wanting to get the DB keys as columns titles in the table and then just the values placed into each column.我想将 DB 键作为表中的列标题,然后将值放入每列。

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).你需要这样的事情,它提供的标题行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