You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask中Jinja模板无法完整打印列表内字典值的问题

问题描述

我需要遍历多个包含单个或多个字典的列表,示例数据如下:

r = [{"symbol":10},{"symbol":15},{"symbol":25}]
h = [{"sy":15},{"sy":23},{"sk":64}]
i = [{"sl":45},{"sl":67},{"sl":98}]

期望输出格式:

Symbol sy sl
10      15  45
15      23  67
25      64  98

我编写的Python代码可正常实现该功能:

for p in r,h,i:
    if p == r:
        print(p[c]["symbol"])
    elif p == h:
        print(p[c]["sy"])
    elif p == i:
        print(p[c]["sl"])

但在使用Flask结合Python后端开发时,Jinja模板仅能输出第一个值,我的Jinja代码如下:

{%set c = 0%}
{% for s in symbol,stockname,shares,price,total%}
<tr>
    {%if s == symbol%}
      <td> {{s[c].symbol}}</td>

    {%if s == stockname %}
      <td> {{s[c].stockname}}</td>

    {%if s == shares %}
      <td> {{s[c].shares}}</td>

    {%if s == price %}
      <td> {{s[c].price}}</td>


    {%if s == total %}
      <td> {{s[c]["total"]}}</td>
</tr>
    {%set c = c + 1%}

    {%endif%}
    {%endif%}
    {%endif%}
    {%endif%}
    {%endif%}

{%endfor%}

</table>
{% endblock %}

请问如何解决Jinja模板无法完整打印列表内字典值的问题?

解决方案

你的Jinja代码逻辑完全颠倒了——当前循环是遍历各个列表(symbol、stockname等),而非遍历每一行的索引;且嵌套的if均为平级关系,导致每次循环仅处理一个列表的单个字段,仅在最后一个if中才递增c,最终只能输出第一行内容。

正确思路是按行索引循环:

  1. 确认所有列表长度一致(若不一致需提前处理),循环每一个索引值
  2. 每个索引对应一行,在该行内依次取出各列表对应索引的字典值

修改后的Jinja代码如下:

<table>
    <!-- 表头 -->
    <tr>
        <th>Symbol</th>
        <th>Stockname</th>
        <th>Shares</th>
        <th>Price</th>
        <th>Total</th>
    </tr>
    <!-- 遍历每一行的索引 -->
    {% for c in range(symbol|length) %}
    <tr>
        <td>{{ symbol[c].symbol }}</td>
        <td>{{ stockname[c].stockname }}</td>
        <td>{{ shares[c].shares }}</td>
        <td>{{ price[c].price }}</td>
        <td>{{ total[c]["total"] }}</td>
    </tr>
    {% endfor %}
</table>
{% endblock %}

注意:后端传递数据时需确保symbol、stockname、shares、price、total这几个列表长度完全一致,避免出现索引越界问题。

内容的提问来源于stack exchange,提问作者Matthew Manning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:25:59