Templating allows data representation in different way, it combines template and data. The template is a document with placeholders, where the actual data will be used, when the template is processed by the template engine. The template can contain control structures like for loops, if statements, etc.
By default Flask uses Jinja2 as its template engine. Jinja2 allows developers to produce different output result file based on simple template text file. In this blog post I will cover how to use:
- rendering templates;
- control structures:
- for loops;
- template inheritance and blocks;
Variables are passed to the template via the context dictionary. In Jinja2 the double curly braces are used as a print statement. So if you want to print the value of the title variable, you should use the following code snippet:
Should you want to access variable’s attributes you have two approaches to achieve that goal:
In case of non-existent variable or attribute, an undefined value will be returned.
To be able to provide a comment in your template file or just to comment out a code block you should surround it with
Control Structures: for loop
for control structure allows loop over a sequence or dictionary of items.
Control Structures: if
if statement is used for branching a logic internally in the template:
Multiple branches can be used in the following way:
Filters allows developers to modify the value of the variable, they are separated by the variable with the pipe symbol ‘|’.
Filters can be chained:
Custom filters can be implemented and used in the templates:
And now you could use it in the following way:
Template Inheritance and Blocks
Template inheritance allows developers to prepare a common layout for the application and to define blocks that could be overridden in the child templates. In the Flask Bookshelf application I have implemented a layout.htm, that contains the skeleton of the web application:
The child templates inherit the base one (layout.htm) and provide their specifics using the defined blocks:
Below I will describe how to structure your Flask application to enable the Jinja2 template engine and use it internally.
Added a templates folder under bookshelf/main
Added a templates folder under bookshelf/admin
The complete demo application, described in this blog post, can be found here.
In the next blog post I will describe how to model your data in your Flask project and use database systems.