Coverage for /Users/davegaeddert/Developer/dropseed/plain/plain/plain/templates/jinja/__init__.py: 39%
41 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 11:16 -0600
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 11:16 -0600
1from importlib import import_module
3from plain.packages import packages
4from plain.runtime import settings
5from plain.utils.functional import LazyObject
6from plain.utils.module_loading import import_string, module_has_submodule
8from .environments import DefaultEnvironment, get_template_dirs
11class JinjaEnvironment(LazyObject):
12 def __init__(self, *args, **kwargs):
13 self.__dict__["_imported_modules"] = set()
14 super().__init__(*args, **kwargs)
16 def _setup(self):
17 environment_setting = settings.TEMPLATES_JINJA_ENVIRONMENT
19 if isinstance(environment_setting, str):
20 env = import_string(environment_setting)()
21 else:
22 env = environment_setting()
24 # We have to set _wrapped before we trigger the autoloading of "register" commands
25 self._wrapped = env
27 def _maybe_import_module(name):
28 if name not in self._imported_modules:
29 import_module(name)
30 self._imported_modules.add(name)
32 for package_config in packages.get_package_configs():
33 if module_has_submodule(package_config.module, "templates"):
34 # Allow this to fail in case there are import errors inside of their file
35 _maybe_import_module(f"{package_config.name}.templates")
37 app = import_module("app")
38 if module_has_submodule(app, "templates"):
39 # Allow this to fail in case there are import errors inside of their file
40 _maybe_import_module("app.templates")
43environment = JinjaEnvironment()
46def register_template_extension(extension_class):
47 environment.add_extension(extension_class)
48 return extension_class
51def register_template_global(value, name=None):
52 """
53 Adds a global to the Jinja environment.
55 Can be used as a decorator on a function:
57 @register_template_global
58 def my_global():
59 return "Hello, world!"
61 Or as a function:
63 register_template_global("Hello, world!", name="my_global")
64 """
65 if callable(value):
66 environment.globals[name or value.__name__] = value
67 elif name:
68 environment.globals[name] = value
69 else:
70 raise ValueError("name must be provided if value is not callable")
72 return value
75def register_template_filter(func, name=None):
76 """Adds a filter to the Jinja environment."""
77 environment.filters[name or func.__name__] = func
78 return func
81__all__ = [
82 "environment",
83 "DefaultEnvironment",
84 "get_template_dirs",
85 "register_template_extension",
86 "register_template_filter",
87 "register_template_global",
88]