我在迭代中遇到问题for loop
在 Flask jinja2 模板中的多个列表上。
我的代码如下所示
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 模板中定义。
一种解决方案是压缩它before 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 %}
另外,你可以添加zip
到 jinja2 全局模板,使用Flask.add_template_x http://flask.pocoo.org/docs/api/#flask.Flask.add_template_filter函数(或Flask.template_x http://flask.pocoo.org/docs/api/#flask.Flask.template_global装饰器)
@app.template_global(name='zip')
def _zip(*args, **kwargs): #to not overwrite builtin zip in globals
return __builtins__.zip(*args, **kwargs)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)