我正面临着在flask 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发布于 2014-01-23 19:11:00
您需要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)发布于 2018-03-23 18:29:05
如果只使用一次zip,并且不想污染全局名称空间,也可以将它作为模板变量传递。
return render_template('form_result.html', ..., zip=zip)https://stackoverflow.com/questions/21306134
复制相似问题