1 # -*- coding: utf-8 -*-
6 This module implements various functions that exposes information about
7 templates that might be interesting for various kinds of applications.
9 :copyright: (c) 2009 by the Jinja2 Team, see AUTHORS for more details.
10 :license: BSD, see LICENSE for more details.
12 from jinja2 import nodes
13 from jinja2.compiler import CodeGenerator
16 class TrackingCodeGenerator(CodeGenerator):
17 """We abuse the code generator for introspection."""
19 def __init__(self, environment):
20 CodeGenerator.__init__(self, environment, '<introspection>',
22 self.undeclared_identifiers = set()
27 def pull_locals(self, frame):
28 """Remember all undeclared identifiers."""
29 self.undeclared_identifiers.update(frame.identifiers.undeclared)
32 def find_undeclared_variables(ast):
33 """Returns a set of all variables in the AST that will be looked up from
34 the context at runtime. Because at compile time it's not known which
35 variables will be used depending on the path the execution takes at
36 runtime, all variables are returned.
38 >>> from jinja2 import Environment, meta
39 >>> env = Environment()
40 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
41 >>> meta.find_undeclared_variables(ast)
44 .. admonition:: Implementation
46 Internally the code generator is used for finding undeclared variables.
47 This is good to know because the code generator might raise a
48 :exc:`TemplateAssertionError` during compilation and as a matter of
49 fact this function can currently raise that exception as well.
51 codegen = TrackingCodeGenerator(ast.environment)
53 return codegen.undeclared_identifiers
56 def find_referenced_templates(ast):
57 """Finds all the referenced templates from the AST. This will return an
58 iterator over all the hardcoded template extensions, inclusions and
59 imports. If dynamic inheritance or inclusion is used, `None` will be
62 >>> from jinja2 import Environment, meta
63 >>> env = Environment()
64 >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
65 >>> list(meta.find_referenced_templates(ast))
68 This function is useful for dependency tracking. For example if you want
69 to rebuild parts of the website after a layout template has changed.
71 for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
73 if isinstance(node.template, nodes.Const) and \
74 isinstance(node.template.value, basestring):
75 yield node.template.value