The Meta API

Changelog

New in version 2.2.

The meta API returns some information about abstract syntax trees thatcould help applications to implement more advanced template concepts. Allthe functions of the meta API operate on an abstract syntax tree asreturned by the Environment.parse() method.

  • 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) == set(['bar'])
  5. True

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.