How to get list of all variables in jinja 2 templates

后端 未结 4 708
南笙
南笙 2020-12-02 16:58

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.

         


        
4条回答
  •  时光说笑
    2020-12-02 17:37

    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.

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

提交回复
热议问题