繁体   English   中英

迭代python中的多个列表 - flask - jinja2模板

[英]Iterating over multiple lists in python - flask - jinja2 templates

我正在尝试迭代在烧瓶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()但它没有在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)

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

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

暂无
暂无

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

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