MCPcopy
hub / github.com/pallets/jinja / find_referenced_templates

Function find_referenced_templates

src/jinja2/meta.py:62–112  ·  view source on GitHub ↗

Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment

(ast: nodes.Template)

Source from the content-addressed store, hash-verified

60
61
62def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:
63 """Finds all the referenced templates from the AST. This will return an
64 iterator over all the hardcoded template extensions, inclusions and
65 imports. If dynamic inheritance or inclusion is used, `None` will be
66 yielded.
67
68 >>> from jinja2 import Environment, meta
69 >>> env = Environment()
70 >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
71 >>> list(meta.find_referenced_templates(ast))
72 ['layout.html', None]
73
74 This function is useful for dependency tracking. For example if you want
75 to rebuild parts of the website after a layout template has changed.
76 """
77 template_name: t.Any
78
79 for node in ast.find_all(_ref_types):
80 template: nodes.Expr = node.template # type: ignore
81
82 if not isinstance(template, nodes.Const):
83 # a tuple with some non consts in there
84 if isinstance(template, (nodes.Tuple, nodes.List)):
85 for template_name in template.items:
86 # something const, only yield the strings and ignore
87 # non-string consts that really just make no sense
88 if isinstance(template_name, nodes.Const):
89 if isinstance(template_name.value, str):
90 yield template_name.value
91 # something dynamic in there
92 else:
93 yield None
94 # something dynamic we don't know about here
95 else:
96 yield None
97 continue
98 # constant is a basestring, direct template name
99 if isinstance(template.value, str):
100 yield template.value
101 # a tuple or list (latter *should* not happen) made of consts,
102 # yield the consts that are strings. We could warn here for
103 # non string values
104 elif isinstance(node, nodes.Include) and isinstance(
105 template.value, (tuple, list)
106 ):
107 for template_name in template.value:
108 if isinstance(template_name, str):
109 yield template_name
110 # something else we don't care about, we could warn here
111 else:
112 yield None

Callers

nothing calls this directly

Calls 1

find_allMethod · 0.80

Tested by

no test coverage detected