2017-03-17 131 views
0

所以即时尝试使用Jinja2从字典列表(由Flask SQL select语句返回)创建一个HTML表。Jinja2字典列表到HTML表格中?

现在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列(其中一个是键和一个是列)。我想获得数据库键作为列标题在表中,然后只是放在每列的值。

这可能吗?因为我想通过密钥的一次迭代?

回答

1

你需要类似这样的东西,它提供了一个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 %} 

+0

这是完美的,是在我的思想路线是。我只是错过了第二个for循环 – msmith1114