I am facing an issue in Iterating for loop
over multiple lists in flask jinja2 template.
My code is something looks like below
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)
I am not sure of coming up with correct template so far,
<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>
Output I am trying to get is something like below in html page
Type - RS
ID - 1001
Status - Failed
ID - 1002
Status - Success
Flask comes packaged with Jinja2, and hence we just need to install Flask. For this series, I recommend using the development version of Flask, which includes much more stable command line support among many other features and improvements to Flask in general.
you need zip()
but it isn't defined in jinja2 templates.
one solution is zipping it before render_template
function is called, like:
view function:
return render_template('form_result.html',type=type,reqIDs_msgs_rcs=zip(IDs,msgs,rcs))
template:
{% for reqID,msg,rc in reqIDs_msgs_rcs %}
<h1>ID - {{ID}}</h1>
{% if rc %}
<h1>Status - {{msg}}!</h1>
{% else %}
<h1> Failed </h1>
{% endif %}
{% endfor %}
also, you can add zip
to jinja2 template global, using Flask.add_template_x
functions(or Flask.template_x
decorators)
@app.template_global(name='zip')
def _zip(*args, **kwargs): #to not overwrite builtin zip in globals
return __builtins__.zip(*args, **kwargs)
You can also pass in zip
as a template variable if you are going to use it just once and prefer not to pollute global namespace.
return render_template('form_result.html', ..., zip=zip)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With