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:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml'])
)
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
:
template = env.get_template('mytemplate.html')
To render it with some variables, just call the render()
method:
print(template.render(the='variables', go='here'))
Using a template loader rather than passing strings to Template
or Environment.from_string()
has multiple advantages. Besides beinga lot easier to use it also enables template inheritance.