skanagasabap
skanagasabap

Reputation: 940

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

Upvotes: 23

Views: 26435

Answers (2)

김민준
김민준

Reputation: 1037

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)

Upvotes: 8

thkang
thkang

Reputation: 11543

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)

Upvotes: 50

Related Questions