【问题标题】:Iterating over multiple lists in python - flask - jinja2 templates迭代python中的多个列表-flask-jinja2模板
【发布时间】:2014-02-13 21:08:11
【问题描述】:

在烧瓶 jinja2 模板中的多个列表上迭代 for loop 时遇到问题。

我的代码如下所示

Type = 'RS'
IDs = ['1001','1002']
msgs = ['Success','Success']
rcs = ['0','1']
return render_template('form_result.html',type=type,IDs=IDs,msgs=msgs,rcs=rcs)

到目前为止,我不确定是否能找到正确的模板,

<html>
  <head>
    <title>Response</title>

  </head>
  <body>
    <h1>Type - {{Type}}!</h1>
    {% for reqID,msg,rc in reqIDs,msgs,rcs %}
    <h1>ID - {{ID}}</h1>
    {% if rc %}
    <h1>Status - {{msg}}!</h1>
    {% else %}
    <h1> Failed </h1>
    {% endif %}
    {% endfor %}
  </body>
</html>

我想要得到的输出类似于下面的 html 页面

Type - RS
 ID   - 1001
 Status - Failed

 ID   - 1002
 Status - Success

【问题讨论】:

  • 你需要使用zip()
  • @KobiK 这也是我的第一个猜测......它抛出错误 UndefinedError: 'zip' is undefined

标签: python flask jinja2


【解决方案1】:

您需要zip(),但它没有在 jinja2 模板中定义。

一种解决方案是在调用render_template函数之前对其进行压缩,例如:

查看功能:

return render_template('form_result.html',type=type,reqIDs_msgs_rcs=zip(IDs,msgs,rcs))

模板:

{% for reqID,msg,rc in reqIDs_msgs_rcs %}
<h1>ID - {{ID}}</h1>
{% if rc %}
<h1>Status - {{msg}}!</h1>
{% else %}
<h1> Failed </h1>
{% endif %}
{% endfor %}

另外,您可以使用Flask.add_template_x 函数(或Flask.template_x 装饰器)将zip 添加到jinja2 模板全局

@app.template_global(name='zip')
def _zip(*args, **kwargs): #to not overwrite builtin zip in globals
    return __builtins__.zip(*args, **kwargs)

【讨论】:

  • 我发现docs.python.org/2/library/__builtin__.html__builtins__ 是Cpython 实现细节,不可移植。我使用了import __builtin__return __builtin__.zip(没有)
  • 你不能用zip代替__builtins__.zip吗?
【解决方案2】:

如果您打算只使用一次并且不希望污染全局命名空间,您也可以将zip 作为模板变量传入。

return render_template('form_result.html', ..., zip=zip)

【讨论】:

  • 这是迄今为止最好的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2014-09-06
  • 2022-11-04
  • 1970-01-01
  • 2021-10-28
  • 2013-12-10
相关资源
最近更新 更多