- Installing and Using
- Variable Interpolation
- Including Files
- Template Inheritance and Blocks
- Control Blocks
Jinja2 is a template engine for Python featuring an optional sandbox environment.
Along with working with the values of variables, Jinja2 can also include other files. Using this functionality, more complex templates can be created and used through combining files containing delimiters and variable interpolation.
From Template() to Environment()
Previously, the function Template() was used to load text before the call to render() to parse it. When dealing with files, this needs to change.
Jinja2 does not automatically use functions for loading files. For that, it provides various Loaders to help with loading files for paring or others to keep in memory for later operations.
To help with the Loaders and other settings, Jinja2 also provides functionality for creating an Environment(). Loaders can be set as part of created an environment. During the process of setting a loader, the path to the template parts can also be set.
Once an environment has been created that has a loader and other settings, it can be used to load templates. For this, the function get_template() is used.
The function get_template() loads a file and makes it ready. Like with using Template(), the function render() can supply variables and starts the process of rendering everything.
In Jinja2, the include keyword can be used within a template to “include” another file within it.
When working with files, this is an easy way to build out from a ‘base’ file and use others as parts like headers and footers.