Reputation: 3092
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()
)
Upvotes: 2
Views: 1916
Reputation: 3092
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
Upvotes: 2