External Exam Download Resources Web Applications Games Recycle Bin

Iterating a list & dictionary in Jinja2 using controlled (for) loop

j2_forloop.py

from flask import *
app = Flask(__name__)

title = "Processing Data with Flask and Jinja2"
words = ["cat","hat","mat"]
lockers = {
            100:"jill",
            101:"mary",
            102:"john"
          }

@app.route("/")
def main():
    return render_template("template.html",
                           title=title,
                           words=words,
                           lockers=lockers)
    
app.run(debug=True)

templates\template.html

<!doctype html>
<h1>{{title}}</h1><br>

{% for each_word in words %}

  <p>{{each_word}}</p><br>

{% endfor %}

{% for each_key in lockers %}

  <p>{{each_key}}, {{lockers[each_key]}}</p>  

{% endfor %}