如何获取Jinja 2模板中所有变量的列表 [英] How to get list of all variables in jinja 2 templates

查看:83
本文介绍了如何获取Jinja 2模板中所有变量的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取模板中所有变量和块的列表.我不想创建自己的解析器来查找变量.我尝试使用以下代码段.

I am trying to get list of all variables and blocks in a template. I don't want to create my own parser to find variables. I tried using following snippet.

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('gummi', 'templates'))
template = env.get_template('chat.html')

template.blocks是键是块的dict,如何获取块内的所有变量?

template.blocks is dict where keys are blocks, how can I get all variables inside the blocks ?

推荐答案

由于没有人回答问题并且我找到了答案

Since no one has answered the question and I found the answer

from jinja2 import Environment, PackageLoader, meta
env = Environment(loader=PackageLoader('gummi', 'templates'))
template_source = env.loader.get_source(env, 'page_content.html')
parsed_content = env.parse(template_source)
meta.find_undeclared_variables(parsed_content)

这将产生未声明变量的列表,因为它不是在运行时执行的,它将产生所有变量的列表.

This will yield list of undeclared variables since this is not executed at run time, it will yield list of all variables.

注意:这将产生使用includeextends包含的html文件.

Note: This will yield html files which are included using include and extends.

这篇关于如何获取Jinja 2模板中所有变量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆