[英]How to read a Jinja2 template and get a list of need variable to render it?
I need to get the list of variable needed in the context of a template to be able to give some feedback to the programmer that will use my service . 我需要获取模板上下文中所需的变量列表,以便能够向使用我的服务的程序员提供一些反馈。
How can I do that ? 我怎样才能做到这一点 ?
I was thinking on giving a context object that will create the variable when the template try to access it and then give me the list of variable in the context object after rendering. 我正在考虑提供一个上下文对象,该对象将在模板尝试访问它时创建变量,然后在渲染后为我提供上下文对象中的变量列表。
Is that possible? 那可能吗?
解析模板,您可以找到所有变量: http : //jinja.pocoo.org/docs/api/#the-meta-api包括示例。
Use jinja2 meta api 使用jinja2 meta api
from jinja2 import Environment, FileSystemLoader,meta
PATH = os.path.dirname(os.path.abspath(__file__)) #get the path of current file
TEMPLATE_ENVIRONMENT = Environment(
autoescape=False,
loader=FileSystemLoader(os.path.join(PATH)),
trim_blocks=False)
template_source =TEMPLATE_ENVIRONMENT.loader.get_source(TEMPLATE_ENVIRONMENT, template_filename)[0] #replace template_filename with your template file relative to current file
parsed_content = TEMPLATE_ENVIRONMENT.parse(template_source)
variables= meta.find_undeclared_variables(parsed_content)
print variables
output : Set of used variables 输出:使用的变量集
set(['CONFIG_PARAM_HTTPS_PROXY_PORT', 'CONFIG_PARAM_HTTP_PROXY_PORT'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.