meta.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.meta
  4. ~~~~~~~~~~~
  5. This module implements various functions that exposes information about
  6. templates that might be interesting for various kinds of applications.
  7. :copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. from jinja2 import nodes
  11. from jinja2.compiler import CodeGenerator
  12. from jinja2._compat import string_types
  13. class TrackingCodeGenerator(CodeGenerator):
  14. """We abuse the code generator for introspection."""
  15. def __init__(self, environment):
  16. CodeGenerator.__init__(self, environment, '<introspection>',
  17. '<introspection>')
  18. self.undeclared_identifiers = set()
  19. def write(self, x):
  20. """Don't write."""
  21. def pull_locals(self, frame):
  22. """Remember all undeclared identifiers."""
  23. self.undeclared_identifiers.update(frame.identifiers.undeclared)
  24. def find_undeclared_variables(ast):
  25. """Returns a set of all variables in the AST that will be looked up from
  26. the context at runtime. Because at compile time it's not known which
  27. variables will be used depending on the path the execution takes at
  28. runtime, all variables are returned.
  29. >>> from jinja2 import Environment, meta
  30. >>> env = Environment()
  31. >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
  32. >>> meta.find_undeclared_variables(ast) == set(['bar'])
  33. True
  34. .. admonition:: Implementation
  35. Internally the code generator is used for finding undeclared variables.
  36. This is good to know because the code generator might raise a
  37. :exc:`TemplateAssertionError` during compilation and as a matter of
  38. fact this function can currently raise that exception as well.
  39. """
  40. codegen = TrackingCodeGenerator(ast.environment)
  41. codegen.visit(ast)
  42. return codegen.undeclared_identifiers
  43. def find_referenced_templates(ast):
  44. """Finds all the referenced templates from the AST. This will return an
  45. iterator over all the hardcoded template extensions, inclusions and
  46. imports. If dynamic inheritance or inclusion is used, `None` will be
  47. yielded.
  48. >>> from jinja2 import Environment, meta
  49. >>> env = Environment()
  50. >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
  51. >>> list(meta.find_referenced_templates(ast))
  52. ['layout.html', None]
  53. This function is useful for dependency tracking. For example if you want
  54. to rebuild parts of the website after a layout template has changed.
  55. """
  56. for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
  57. nodes.Include)):
  58. if not isinstance(node.template, nodes.Const):
  59. # a tuple with some non consts in there
  60. if isinstance(node.template, (nodes.Tuple, nodes.List)):
  61. for template_name in node.template.items:
  62. # something const, only yield the strings and ignore
  63. # non-string consts that really just make no sense
  64. if isinstance(template_name, nodes.Const):
  65. if isinstance(template_name.value, string_types):
  66. yield template_name.value
  67. # something dynamic in there
  68. else:
  69. yield None
  70. # something dynamic we don't know about here
  71. else:
  72. yield None
  73. continue
  74. # constant is a basestring, direct template name
  75. if isinstance(node.template.value, string_types):
  76. yield node.template.value
  77. # a tuple or list (latter *should* not happen) made of consts,
  78. # yield the consts that are strings. We could warn here for
  79. # non string values
  80. elif isinstance(node, nodes.Include) and \
  81. isinstance(node.template.value, (tuple, list)):
  82. for template_name in node.template.value:
  83. if isinstance(template_name, string_types):
  84. yield template_name
  85. # something else we don't care about, we could warn here
  86. else:
  87. yield None