繁体   English   中英

带有 Flask 的 Jinja Table 嵌套字典

[英]Nested Dictionary to Jinja Table w/ Flask

我对 web dev/Flask/HTML 很陌生,所以如果我的问题没有明确说明,请提前道歉。 我有一个具有以下结构的嵌套字典:

dict = {"12-30-2019": 
             {"Meat": 
                     "Calories": 800,
                     "Protein": 20,
                     "Fat": 10
             },
             {"Potato": 
                     "Calories": 200,
                     "Protein": 15,
                     "Fat": 12
             }
       }

dict={'12-30-2019': {'meat': {'Calories' : 800, 'Protein': 20, 'Fat': 10}, 'Potato': {'Calories': 200, 'Protein': 15, 'Fat': 12}}} 

我正在努力设计这样的模板:

       |            Date          |
       ----------------------------
       | Calories | Protein | Fat |
-----------------------------------
Meat   |   800    |    20   |  10 | 
-----------------------------------
Potato |   200    |    15   |  12 |

到目前为止,我失败的尝试是这样的:

    <table>
        {% for parent_key, parent_value in mfp_data.items() %}
        <th> {{ parent_key }}</th>
        <tr>
            {% for child_key, child_value in parent_value.items() %}
                <th> {{ child_key }} </th>
                {% for baby_key, baby_value in child_value.items() %}
                <th> {{ baby_key }} </th>
                <td> {{ baby_value }}</td>
                {% endfor %}
            {% endfor %}
        </tr>
        {% endfor %}
    </table>

关于我如何优雅地做到这一点的任何建议?

理想情况下,您应该在将数据传递到模板/视图/HTML 部分之前,将这些数据从相对复杂的字典转换为模板可以简单读取和显示的结构。 您希望模板部分中的逻辑尽可能少,并且只迭代预制列表。

这是部分做到这一点的解决方案。 它将日期和行标题提取到单独的变量中,以便在模板中轻松访问它们。

@app.route('/')
def hello_world():
    data = {
        '12-30-2019': {'meat': {'Calories': 800, 'Protein': 20, 'Fat': 10}, 'Potato': {'Calories': 200, 'Protein': 15, 'Fat': 12}},
        '12-31-2019': {'meat': {'Calories': 800, 'Protein': 20, 'Fat': 10}, 'Potato': {'Calories': 200, 'Protein': 15, 'Fat': 12}},
    }

    dates = data.keys()
    row_headers = list(list(data.values())[0].values())[0].keys()

    return render_template("index.html", dates=dates, row_headers=row_headers, mfp_data=data)
<table>
  {% for date in dates %}
    <tr><th colspan="3">{{ date }}</th></tr>
    <tr>
      <th></th>
      {% for row_header in row_headers %}
        <th>{{ row_header }}</th>
      {% endfor %}
    </tr>

    {% for key, values in mfp_data[date].items() %}
      <tr>
        <th>{{ key }}</th>
      {% for value in values.values() %}
        <td>
        {{ value }}
        </td>
      {% endfor %}
      </tr>
    {% endfor %}
  {% endfor %}
</table>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM