2017-03-17 35 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