在Python中遍历多个列表 - Flask - Jinja2模板

22

我在使用Flask Jinja2模板遍历多个列表时遇到了问题。我的代码类似于以下内容:

```

{% for item1, item2 in zip(list1, list2) %}

{{ item1 }} - {{ item2 }}

{% endfor %}

```

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

1
你需要使用 zip() - Kobi K
1
@KobiK 那也是我的第一个猜测... 它会抛出错误 UndefinedError: 'zip' 未定义 - skanagasabap
2个回答

49

你需要使用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装饰器)向jinja2模板全局中添加zip

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

我发现 https://docs.python.org/2/library/__builtin__.html 上说 __builtins__ 是 CPython 的实现细节,不具备可移植性。我使用了 import __builtin__return __builtin__.zip(没有 s)。 - dajobe
你不能只使用 zip 代替 __builtins__.zip 吗? - bfontaine

8

如果您只需要使用一次并且不想污染全局命名空间,您也可以将zip作为模板变量传递。

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

2
这绝对是最好的答案。谢谢! - Russell Lego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接