When we are developing web pages with the Flask framework in Python we can easily create templates. And it is very typical that we want to list a set of elements within the template. In this example we are going to see how we can create templates with lists in Flask.
Create the Route
The first thing will be to create our Flask application.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def helloworld():
return 'Hello'
if __name__ == '__main__':
app.run()
What we can see is that our Flask application has a path to the root of the project that simply shows us a “Hello” and the last line that does is start the application. At that moment you can access port 5000 of the machine to see the application running.
The next step will be to create a list element within the route method.
@app.route('/')
def helloworld():
list = {'A','B','C','D'}
return 'Hello'
Now we have to pass this list to a template. We are going to assume that we have a template called list.html that we will now define. We will need the render_template method to be able to call the template.
The render_template method must be imported from the Flask library.
from flask import Flask, render_template
And now we invoke it…
def helloworld():
list = {'A','B','C','D'}
return render_template('list.html',list=list)
We see that as a parameter we pass the list of elements that we have created.
Template with the list
Now we are going to define the template lista.html. This template must be inside the templates directory.
/
/templates
The template will be able to access the list that we have passed to it in the variable list. What we will have to do is go through this list using the for control structure
- {% for element in list %}
- {{ element }}
{% endfor %}
To present the elements we must show the variable in braces, with two braces on each side.
With this we will know how to create templates with lists in Flask.
