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
1 2 3 4 5 6 7 8 9 10
The HTML parts of the template should be familiar; the new feature is the content in
curly braces. The items
content are variables that can be set in your
Python code and passed as parameters to the template. Save the code above as
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
`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.
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.