Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over multiple lists in python - flask - jinja2 templates

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
like image 578
skanagasabap Avatar asked Jan 23 '14 10:01

skanagasabap


People also ask

Does Jinja2 have flask?

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.


2 Answers

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)
like image 177
thkang Avatar answered Oct 12 '22 23:10

thkang


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)
like image 41
김민준 Avatar answered Oct 12 '22 23:10

김민준