元 API

New in version 2.2.

元 API 返回一些关于抽象语法树的信息,这些信息能帮助应用实现更多的高级模板概念。所有的元 API 函数操作一个 Environment.parse() 方法返回的抽象语法树。

  • jinja2.meta.findundeclared_variables(_ast)
  • Returns a set of all variables in the AST that will be looked up fromthe context at runtime. Because at compile time it’s not known whichvariables will be used depending on the path the execution takes atruntime, all variables are returned.
  1. >>> from jinja2 import Environment, meta
  2. >>> env = Environment()
  3. >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
  4. >>> meta.find_undeclared_variables(ast)
  5. set(['bar'])

Implementation

Internally the code generator is used for finding undeclared variables.This is good to know because the code generator might raise aTemplateAssertionError during compilation and as a matter offact this function can currently raise that exception as well.

  • jinja2.meta.findreferenced_templates(_ast)
  • Finds all the referenced templates from the AST. This will return aniterator over all the hardcoded template extensions, inclusions andimports. If dynamic inheritance or inclusion is used, None will beyielded.
  1. >>> from jinja2 import Environment, meta
  2. >>> env = Environment()
  3. >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
  4. >>> list(meta.find_referenced_templates(ast))
  5. ['layout.html', None]

This function is useful for dependency tracking. For example if you wantto rebuild parts of the website after a layout template has changed.