神社和嵌套的字典

时间:2020-02-20 13:39:02

标签: python flask jinja2

我希望从嵌套字典中使用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和这种类型的嵌套字典一起循环: {1:{'A':'item1 A','B':'item1 B'},2:{'a':'item2 A','b':'Item2 B','c':'Item2 C'},...}

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

提前考虑

1 个答案:

答案 0 :(得分:0)

有很多方法可以在python中的嵌套字典中进行迭代,但是我不认为这可以在flask的模板中完成。

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

例如

pattern

成为

<input type="date" pattern="[0-9]{2}.[0-9]{2}.[0-9]{4}">

在模板中迭代:

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

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

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

请参见here