Learning Jinja2: Part 3: Including Files

Learning Jinja2

Jinja2 is a template engine for Python featuring an optional sandbox environment.


Including Files

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.

get_template()

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.

Include

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.

Play with the example on Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.