v0.166.0
 1from typing import Any
 2
 3from jinja2 import nodes
 4from jinja2.ext import Extension
 5from jinja2.runtime import Context
 6
 7
 8class InclusionTagExtension(Extension):
 9    """Intended to be subclassed"""
10
11    # tags = {'inclusion_tag'}
12    tags: set[str]
13    template_name: str
14
15    def parse(self, parser: Any) -> nodes.Node:
16        lineno = next(parser.stream).lineno
17        args: list[nodes.Expr] = [
18            nodes.DerivedContextReference(),
19        ]
20        kwargs = []
21        while parser.stream.current.type != "block_end":
22            if parser.stream.current.type == "name":
23                key = parser.stream.current.value
24                parser.stream.skip()
25                parser.stream.expect("assign")
26                value = parser.parse_expression()
27                kwargs.append(nodes.Keyword(key, value))
28            else:
29                args.append(parser.parse_expression())
30
31        call = self.call_method("_render", args=args, kwargs=kwargs, lineno=lineno)
32        return nodes.CallBlock(call, [], [], []).set_lineno(lineno)
33
34    def _render(self, context: Context, *args: Any, **kwargs: Any) -> str:
35        render_context = self.get_context(context, *args, **kwargs)
36        template = self.environment.get_template(self.template_name)
37        return template.render(render_context)
38
39    def get_context(
40        self, context: Context, *args: Any, **kwargs: Any
41    ) -> Context | dict[str, Any]:
42        raise NotImplementedError(
43            "You need to implement the `get_context` method in your subclass."
44        )