Expose the Jinja environment as Template.jinja_env

This commit is contained in:
Miguel Grinberg
2025-03-02 11:53:54 +00:00
parent 68a53a7ae7
commit 953dd94321

View File

@@ -1,19 +1,26 @@
from jinja2 import Environment, FileSystemLoader, select_autoescape from jinja2 import Environment, FileSystemLoader, select_autoescape
_jinja_env = None
class Template: class Template:
"""A template object. """A template object.
:param template: The filename of the template to render, relative to the :param template: The filename of the template to render, relative to the
configured template directory. configured template directory.
:param kwargs: any additional options to be passed to the Jinja
environment's ``get_template()`` method.
""" """
#: The Jinja environment.
jinja_env = None
@classmethod @classmethod
def initialize(cls, template_dir='templates', enable_async=False, def initialize(cls, template_dir='templates', enable_async=False,
**kwargs): **kwargs):
"""Initialize the templating subsystem. """Initialize the templating subsystem.
This method is automatically invoked when the first template is
created. The application can call it explicitly if custom options need
to be provided.
:param template_dir: the directory where templates are stored. This :param template_dir: the directory where templates are stored. This
argument is optional. The default is to load argument is optional. The default is to load
templates from a *templates* subdirectory. templates from a *templates* subdirectory.
@@ -23,20 +30,19 @@ class Template:
:param kwargs: any additional options to be passed to Jinja's :param kwargs: any additional options to be passed to Jinja's
``Environment`` class. ``Environment`` class.
""" """
global _jinja_env cls.jinja_env = Environment(
_jinja_env = Environment(
loader=FileSystemLoader(template_dir), loader=FileSystemLoader(template_dir),
autoescape=select_autoescape(), autoescape=select_autoescape(),
enable_async=enable_async, enable_async=enable_async,
**kwargs **kwargs
) )
def __init__(self, template): def __init__(self, template, **kwargs):
if _jinja_env is None: # pragma: no cover if self.jinja_env is None: # pragma: no cover
self.initialize() self.initialize()
#: The name of the template #: The name of the template.
self.name = template self.name = template
self.template = _jinja_env.get_template(template) self.template = self.jinja_env.get_template(template, **kwargs)
def generate(self, *args, **kwargs): def generate(self, *args, **kwargs):
"""Return a generator that renders the template in chunks, with the """Return a generator that renders the template in chunks, with the