Basics

Jinja2 uses a central object called the template Environment.Instances of this class are used to store the configuration and global objects,and are used to load templates from the file system or other locations.Even if you are creating templates from strings by using the constructor ofTemplate class, an environment is created automatically for you,albeit a shared one.

Most applications will create one Environment object on applicationinitialization and use that to load templates. In some cases however, it’suseful to have multiple environments side by side, if different configurationsare in use.

The simplest way to configure Jinja2 to load templates for your applicationlooks roughly like this:

  1. from jinja2 import Environment, PackageLoader, select_autoescape
  2. env = Environment(
  3. loader=PackageLoader('yourapplication', 'templates'),
  4. autoescape=select_autoescape(['html', 'xml'])
  5. )

This will create a template environment with the default settings and aloader that looks up the templates in the templates folder inside theyourapplication python package. Different loaders are availableand you can also write your own if you want to load templates from adatabase or other resources. This also enables Autoescaping forHTML and XML files.

To load a template from this environment you just have to call theget_template() method which then returns the loaded Template:

  1. template = env.get_template('mytemplate.html')

To render it with some variables, just call the render() method:

  1. print(template.render(the='variables', go='here'))

Using a template loader rather than passing strings to Templateor Environment.from_string() has multiple advantages. Besides beinga lot easier to use it also enables template inheritance.