How to pass items to loop using Jinja2/Flask?

16,506

This code is totally valid. The important thing is to restart the server if you do changes to lists or dictionaries.

Apart from that, in Flask you can pass any type that is built into Python, be it a list, a dictionary or a tuple.

Here are short example for each of the types that pass more or less the same content:

from flask import Flask, render_template

adictionary = {'spam': 1, 'eggs': 2}
alist = ['Eins', 'Zwei', 'Drei']
atuple = ('spam', 'eggs')

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('base.html', pages=alist)


@app.route('/tuple/')
def tuple():
    return render_template('base.html', pages=atuple)


@app.route('/dict/')
def adict():
    return render_template('base.html', pages=adictionary)

if __name__ == "__main__":
    app.run(port=8000)
Share:
16,506
mcbetz
Author by

mcbetz

Updated on June 09, 2022

Comments

  • mcbetz
    mcbetz almost 2 years

    I want to pass a list of pages and loop it in Jinja2 to show all pages of my website. I use Flask to construct and run the app. I followed the official flask documentation, together with this tutorial. However when I try to pass the list and try to loop over it, it does not appear in the rendered html.

    What am I doing wrong? How to properly pass the list and loop over it using base.html as a template?

    Here is my code with a dummy page list hardcoded:

    app.py:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        page_list = ['Eins', 'Zwei']
        return render_template('base.html', pages=page_list)
    
    
    if __name__ == "__main__":
        app.run(port=8000)
    

    And base.html, located in /templates/:

    <html>
    <head>
    <title>Test</title>
    </head>
    
    <body>
    <h1>All the nice pages</h1>
    {% for page in pages %}
    <p>{{ page }}</p>
    {% endfor %}
    </body>
    </html>
    

    When I run the app and browse to http://127.0.0.1:8000/, this is what I get:

    <html>
    <head>
    <title>Test</title>
    </head>
    
    <h1>All the nice pages</h1>
    <body>
    
    </body>
    </html>