Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass items to loop using Jinja2/Flask?

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>
like image 761
mcbetz Avatar asked Jan 16 '14 16:01

mcbetz


1 Answers

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)
like image 96
mcbetz Avatar answered Nov 14 '22 22:11

mcbetz