|
| 1 | +from jinja2 import Environment, BaseLoader, select_autoescape |
| 2 | +from textcompose.content.content import BaseContent, Value, Condition |
| 3 | + |
| 4 | +TEXTCOMPOSE_JINJA_ENV_FIELD = "textcompose_jinja_env" |
| 5 | + |
| 6 | + |
| 7 | +class Jinja(BaseContent): |
| 8 | + def __init__(self, template: Value, when: Condition | None = None): |
| 9 | + self.template = template |
| 10 | + super().__init__(when=when) |
| 11 | + |
| 12 | + def render(self, data: dict, **kwargs) -> str: |
| 13 | + if TEXTCOMPOSE_JINJA_ENV_FIELD in kwargs: |
| 14 | + env = kwargs[TEXTCOMPOSE_JINJA_ENV_FIELD] |
| 15 | + else: |
| 16 | + kwargs[TEXTCOMPOSE_JINJA_ENV_FIELD] = default_env |
| 17 | + env = default_env |
| 18 | + |
| 19 | + template = env.get_template(self.template) |
| 20 | + |
| 21 | + return template.render(data) |
| 22 | + |
| 23 | + |
| 24 | +class StubLoader(BaseLoader): |
| 25 | + def get_source(self, environment, template): |
| 26 | + del environment # unused |
| 27 | + return template, template, lambda: True |
| 28 | + |
| 29 | + |
| 30 | +def _create_env(*args, filters=None, **kwargs) -> Environment: |
| 31 | + env = Environment(loader=StubLoader(), autoescape=select_autoescape(["html", "xml"]), *args, **kwargs) |
| 32 | + |
| 33 | + if filters: |
| 34 | + env.filters.update(filters) |
| 35 | + |
| 36 | + return env |
| 37 | + |
| 38 | + |
| 39 | +default_env = _create_env() |
0 commit comments