Jinja and nested dict



我想从嵌套dict:中用Flask(jinja(在html中打印一个表

Python部分:

@app.route("/")
def index():
#the nested dict exemple:
dict_temp = {0: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total':
''}, 1: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}, 2: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}}
parent_dict = dict_temp
return render_template("test.html", parent_dict = parent_dict)

Jinja模板与表格:

<table style="width:100%">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Shares</th>
<th>Price</th>
<th>Total</th>
</tr>
{% for dict_item in parent_dict %}
<tr>
{% for key, value in dict_item.items() %}
<td>{{value}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

代码与这个python一起工作:

parent_dict = [{'A':'item1 A','B':'item1 B'},{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}]

我如何使用jinja和这种类型的嵌套dict进行循环:

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

或者我必须以不同的方式构建我的输入?

有一些方法可以迭代python中的嵌套dict,但我认为这不能在flask中的模板中完成。

正如您所建议的,您可以使用dict方法的列表,如上所示。

例如

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

成为

[{'A':'item1 A','B':'item1 B'}, {'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... ]

在模板中循环:

{% for dict_item in list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}

您可以执行以下操作将dict的dict转换为dict 的列表

list_of_dics = [value for value in dic_of_dics.values()]

参见此处

最新更新