Skip to content

Templates

The hello_world() endpoint in the default application returns a simple text string which appears in the browser window. This shows that the application is working, but we need more control over the format of the page content. This is especially true when we come to return and present rows of data from the database.

Flask makes use of the jinja2 template language to wrap the page content in HTML. We will use the example template below to improve the presentation of the output from hello_world().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ content }}</h1>
</body>
</html>

The HTML parts of the template should be familiar; the new feature is the content in curly braces. The items title and content are variables that can be set in your Python code and passed as parameters to the template. Save the code above as templates/index.html.

Flask provides a utility function for rendering templates. The listing below shows a modified version of run.py where the simple text output is replaced by a call to render_template().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os
from flask import render_template

from app import create_app

config_name = os.getenv('FLASK_ENV')
app = create_app(config_name)


@app.route('/')
def hello_world():
    return render_template('index.html',
                           title="Welcome",
                           content="Hello World!")

if __name__ == '__main__':
    app.run()

`The changes are:

Line 2: We need to import the utility function

Lines 12 - 14: The endpoint returns the output from the render_template() function. Note that the template parameters are passed in as key-value pairs.

Update the run.py file to match the code above, restart the application and refresh the page in your browser. This time, the string Hello World! will appear as an HTML level 1 heading.

Jinja2 allows you to process complex structures such as arrays of data from the database and Python objects. Using simple loops and conditions, you can render your data just how you want to. We will be making use of some of the more complex features of jinja2 in later parts of the tutorial. If you want to find out more right now, please use the link below.

Further reading

 Jinja2 templates