Any way to get variables keys from jinja2 template string?

↘锁芯ラ 提交于 2020-01-06 06:24:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/48685227/any-way-to-get-variables-keys-from-jinja2-template-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!