Reputation: 1132
Here is the code snippet I have initialized jinja2 template
from jinja2 import Template
templ = Template("{{foo}} to {{bar}}")
And I am willing to extract the template string variable keys from the template obj as below.
templ.keys() == ["foo", "bar"]
Is there any API to make it work? I have searched for a long while but got nothing work.
Upvotes: 6
Views: 4703
Reputation: 46849
using jinja2.meta
you could:
from jinja2 import Environment, meta
templ_str = "{{foo}} to {{bar}}"
env = Environment()
ast = env.parse(templ_str)
print(meta.find_undeclared_variables(ast)) # {'bar', 'foo'}
which returns the set
of the undeclared variables.
you could also use the re
gex module to find the variable names in your template string:
from jinja2 import Template
import re
rgx = re.compile('{{(?P<name>[^{}]+)}}')
templ_str = "{{foo}} to {{bar}}"
templ = Template(templ_str)
variable_names = {match.group('name') for match in rgx.finditer(templ_str)}
print(variable_names) # {'foo', 'bar'}
the regex (could probably be better...) matches {{
followed by anything that is not a curly bracket until }}
is encountered.
Upvotes: 11