Ryan Chou
Ryan Chou

Reputation: 1132

Any way to get variables keys from jinja2 template string?

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

Answers (1)

hiro protagonist
hiro protagonist

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 regex 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

Related Questions