Skip to content

Templates

Flask can return, instead of text, a template, that is html code from a specific file (by default placed in the "templates" folder):

from flask import Flask, render_template      

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html")

if __name__ == "__main__":
    app.run(debug=True)

the render_template function allows you to pass the name of the template, ie the file that exists in the "templates" folder. Flask will just show this file after visiting http://localhost:5000/.

The render_template function allows you to pass named arguments that build what we call "context". This context is the data that will be available in the template that is passed in the first argument.

Since you can pass context to a template, you can probably do something with this data in the template, right? Yes of course!

Assuming the call to render_template would be:

return render_template('index.html', title='Home', user='Matheo')

then in the file "index.html" you will be able to write the following data:

<title>{{ title }} - Microblog</title>
<h1>Hello, {{ user }}!</h1>

Conditional statements

You can use ifs in templates. The syntax is simple, and for a call to render_template like in the previous paragraph, it could look like this:

{% if title %}
<title>{{ title }} - Microblog</title>
% else %}
<title>Welcome to Microblog</title>
{% endif %}

Loops

Let's assume that we call render_template like this:

return render_template("template.html", texts=['first', 'second'])

We can refer to such a variable in the template like this:

{% for txt in texts %}
    <h2> {{ txt }} </h2>
{% endfor %}

that is, just by iterating.