HTML templates

Templates can be used to generate any type of text file. For web applications, you’ll primarily be generating HTML pages, but you can also generate markdown, plain text for emails, any anything else.

To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments.

All templates must be in the templates folder: /templates

Flask uses the Jinja template library to render templates.

Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between {{ and }} is an expression that will be output to the final document. {% and %} denotes a control flow statement like if and for. Unlike Python, blocks are denoted by start and end tags rather than indentation since static text within a block could change indentation.

Conditional templates

templates/index.html
<h1>Message for you</h1>
<p>{{ message }}</p>
{% if valid %}
<p>Valid!</p>
{% else %}
<p>Not valid!</p>
{% endif %}
from flask import Flask, render_template

# ...

@app.route('/')
def home():
    return render_template("index.html", message="Hi everyone!", valid=True)

Further reading

Last updated