2

I have a template, say with one variable NAME

my_template = "Hello {{ NAME }}"

Eventually the code will render the template, eg:

from jinja2 import Template
template = Template(my_template)
// what code would return 'NAME' here?
rendered = template.render(NAME="frank")

I need to get the list of variables / "available args" to the template. In this case, this would return NAME (likely in a collection of some sort).

(My detailed use case is I accept templates that may, optionally, include some well-known template-variable names, which I need to pull out, and then add to the context as i call render())

some bits flipped
  • 2,592
  • 4
  • 27
  • 42
  • I think it's a duplicate of [this](https://stackoverflow.com/questions/3398850/how-to-get-a-list-of-current-variables-from-jinja-2-template), though maybe something has changed in the 8 years passed since then. – 9000 Sep 10 '18 at 19:07

1 Answers1

2

I was blocked on this, so eventually found the answer. This requires jinja2.meta

from jinja2 import Template, Environment, meta
env = Environment()
ast = env.parse(code_string)
for var in meta.find_undeclared_variables(ast):
    print(var)   # <-----
template = Template(code_string)
template.render( # ... args
some bits flipped
  • 2,592
  • 4
  • 27
  • 42