3

I'm trying to get a list of variables from a Jinja2 template.

test1.j2:

some-non-relevant-content
{{var1}}
{% include 'test2.j2' %}

test2.j2:

another-text
{{var2}}

I can get variables from test1 easily:

env = Environment(loader=FileSystemLoader(searchpath='./Templates'))
src_t = env.loader.get_source(env, 'test1.j2')[0]
parsed_t = env.parse(source=src_t)
t_vars = meta.find_undeclared_variables(ast=parsed_t)

Problem is, I can only get variables from the parent template with get_source. Obviously, I can not feed class template object to parse method as well.

Is there any way to build the full list? {'var1', 'var2'} in my case. Ideally by using Jinja2 API. Minimum custom code.

secret
  • 61
  • 6

1 Answers1

3

Found a way to code that without a big pain. meta.find_referenced_templates helps to load all child templates when applied recursively. When done, it's trivial to get variables from all templates in a single list.

secret
  • 61
  • 6