Iterate over multiple lists in python-flask templates - jinja2

I ran into a problem in Iterating for loopover several lists in a jinja2 flask template.

My code looks something like

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'm not sure I’ll come up with the right template,

<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>

The output I'm trying to get is something like below on the html page

Type - RS
 ID   - 1001
 Status - Failed

 ID   - 1002
 Status - Success
+4
source share
2 answers

you need zip(), but it is not defined in jinja2 templates.

one solution encrypts it before render_template , like:

viewing 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 %}

you can add zipjinja2 global to the template using Flask.add_template_xfunctions (or Flask.template_xdecorators)

@app.template_global(name='zip')
def _zip(*args, **kwargs): #to not overwrite builtin zip in globals
    return __builtins__.zip(*args, **kwargs)
+15
source

zip , .

return render_template('form_result.html', ..., zip=zip)
0

Source: https://habr.com/ru/post/1523314/


All Articles