【问题标题】:For loop in Jinja2/python not working (using sqlite3)Jinja2/python 中的 For 循环不起作用(使用 sqlite3)
【发布时间】:2018-10-12 18:54:37
【问题描述】:

我在 jinja 中有以下 for 循环:

<table>
   <thead>
       <td>Stock</td>
       <td>Shares</td>
       <td>Total</td>
   </thead>
   <tbody>
       {% for dict in rows2 %}
       <tr>
           {% for key, value in dict.items() %}
           <td> {{value}} </td>
           {% endfor %}
       </tr>
       {% endfor %}
   </tbody>
</table>

它从我的烧瓶应用程序中获取数据,尤其是从以下行:

rows2 = db.execute("SELECT stock, amount, total_value FROM portfolio WHERE id = :id", id = session.get("user_id"))

现在,如果我将 rows2 打印到控制台,我实际上得到了我想要的,就像这样:

[{'stock': 'AAPL', 'amount': 1, 'total_value': 676.4}, {'stock': 'BB', 'amount': 1, 'total_value': 10.53}, {'stock': 'IBM', 'amount': 1, 'total_value': 144.99}]

但网页中的表格只显示表头部分,实际数据部分留空!为什么会这样?

干杯!

【问题讨论】:

  • 您是否将rows2 正确传递给渲染调用?
  • 我猜是吗? return render_template("portfolio.html") 其中,portfolio 是表格所在的文件。
  • 将代码发布为您如何呈现模板?

标签: python sqlite flask jinja2


【解决方案1】:

根据您的评论,我认为罪魁祸首是您致电render_template()。您不仅需要传递模板名称,还需要模板中使用的变量See here for the flask-docs

所以你实际上应该这样做

return render_template("portfolio.html", rows2=rows2)

...其中左侧是模板中的名称,右侧是您在逻辑中分配给的变量。

【讨论】:

  • @JustABeginner,根据您对渲染的评论,我完全改变了我的答案。这有帮助吗?
  • 耶耶耶!!!有用! :D 谢谢你!!!我不知道我必须传递参数,这似乎有点多余,因为变量 rows2 已经在覆盖“主页”路由的应用程序部分中!
【解决方案2】:

在 items() 之后省略 ():

{% for key, value in dict.items %}
....
{% endif %}

【讨论】:

  • 试过了,不幸的是它似乎仍然没有显示任何数据:/
猜你喜欢
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
相关资源
最近更新 更多