Coverage for /Users/davegaeddert/Developer/dropseed/plain/plain/plain/templates/jinja/__init__.py: 73%

1 from importlib import import_module

2

3 from plain.packages import packages

4 from plain.runtime import settings

5 from plain.utils.functional import LazyObject

6 from plain.utils.module_loading import import_string, module_has_submodule

7

8 from .environments import DefaultEnvironment, get_template_dirs

9

10

11 class JinjaEnvironment(LazyObject):

12 def __init__(self, *args, **kwargs):

13 self.__dict__["_imported_modules"] = set()

14 super().__init__(*args, **kwargs)

15

16 def _setup(self):

17 environment_setting = settings.TEMPLATES_JINJA_ENVIRONMENT

18

19 if isinstance(environment_setting, str):

20 env = import_string(environment_setting)()

21 else:

22 env = environment_setting()

23

24 # We have to set _wrapped before we trigger the autoloading of "register" commands

25 self._wrapped = env

26

27 def _maybe_import_module(name):

28 if name not in self._imported_modules:

29 import_module(name)

30 self._imported_modules.add(name)

31

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")

36

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")

41

42

43 environment = JinjaEnvironment()

44

45

46 def register_template_extension(extension_class):

47 environment.add_extension(extension_class)

48 return extension_class

49

50

51 def register_template_global(value, name=None):

52 """

53 Adds a global to the Jinja environment.

54

55 Can be used as a decorator on a function:

56

57 @register_template_global

58 def my_global():

59 return "Hello, world!"

60

61 Or as a function:

62

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")

71

72 return value

73

74

75 def 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

79

80

81 __all__ = [

82 "environment",

83 "DefaultEnvironment",

84 "get_template_dirs",

85 "register_template_extension",

86 "register_template_filter",

87 "register_template_global",

88]