Add support for a {% debug %} extension tag.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This dumps the available variables, filters and tests.
authored by Shaheed Haque · committed by David Lord · parent 496c81a · Browse files · 2 files·+80 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+80 added−2 removed
- tests:+16 added−0 removed
- other:+64 added−2 removed
Provenance
- Commit
017c8d3- Tree
eab82aa- Author
Shaheed Haque <srhaque@theiet.org>- Committer
David Lord <davidism@gmail.com>- Parent
496c81a
2 files changed+80 added−2 removed
modified:jinja2/ext.py+64 added-2 removed
2 unmodified lines3 jinja2.ext4 ~~~~~~~~~~5 6 Jinja extensions allow to add custom tags similar to the way django custom7- tags work. By default two example extensions exist: an i18n and a cache8- extension.7+ tags work. The following default example extensions are included:8 9+ - a i18n support {% trans %} tag10+ - a {% do %} tag11+ - loop control {% break %} and {% continue %} tags12+ - a {% debug %} tag13+14 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD.16 """17+import pprint18 import re19+from sys import version_info20 21 from jinja2 import nodes22 from jinja2.defaults import BLOCK_START_STRING, \23 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \24 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \25 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \26 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS27 from jinja2.environment import Environment28+from jinja2.nodes import ContextReference29 from jinja2.runtime import concat30 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError31 from jinja2.utils import contextfunction, import_string, Markup32 from jinja2._compat import with_metaclass, string_types, iteritems33+from markupsafe import escape34 35 36 # the only real useful gettext functions for a Jinja template. Note37 # that ugettext must be assigned to gettext as Jinja doesn't support403 unmodified lines441 class AutoEscapeExtension(Extension):442 pass443 444 445+class DebugExtension(Extension):446+ """447+ A ``{% debug %}`` tag that dumps the available variables, filters and tests.448+ Typical usage like this:449+450+ .. codeblock:: html+jinja451+ <pre>{% debug %}</pre>452+453+ produces output like this:454+455+ ::456+ {'context': {'_': <function _gettext_alias at 0x7f9ceabde488>,457+ 'csrf_token': <SimpleLazyObject: 'lfPE7al...q3bykS4txKfb3'>,458+ 'cycler': <class 'jinja2.utils.Cycler'>,459+ ...460+ 'view': <polls.views_auth.Login object at 0x7f9cea2cbe48>},461+ 'filters': ['abs', 'add', 'addslashes', 'attr', 'batch', 'bootstrap',462+ 'bootstrap_classes', 'bootstrap_horizontal',463+ 'bootstrap_inline', ... 'yesno'],464+ 'tests': ['callable', 'checkbox_field', 'defined', 'divisibleby',465+ 'escaped', 'even', 'iterable', 'lower', 'mapping',466+ 'multiple_checkbox_field', ... 'string', 'undefined', 'upper']}467+468+ """469+ tags = {'debug'}470+471+ def __init__(self, environment):472+ super(DebugExtension, self).__init__(environment)473+474+ def parse(self, parser):475+ lineno = parser.stream.expect('name:debug').lineno476+ context = ContextReference()477+ call = self.call_method('_render', [context], lineno=lineno)478+ return nodes.Output([nodes.MarkSafe(call)])479+480+ def _render(self, context):481+ result = {482+ 'filters': sorted(self.environment.filters.keys()),483+ 'tests': sorted(self.environment.tests.keys()),484+ 'context': context.get_all()485+ }486+ #487+ # We set the depth since the intent is basically to show the top few488+ # names. TODO: provide user control over this?489+ #490+ if version_info[:2] >= (3,4):491+ text = pprint.pformat(result, depth=3, compact=True)492+ else:493+ text = pprint.pformat(result, depth=3)494+ text = escape(text)495+ return text496+497+498 def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,499 babel_style=True):500 """Extract localizable strings from the given template node. Per501 default this function returns matches in babel style that means non string183 unmodified lines685 do = ExprStmtExtension686 loopcontrols = LoopControlExtension687 with_ = WithExtension688 autoescape = AutoEscapeExtension689+debug = DebugExtensionmodified:tests/test_ext.py+16 added
238 unmodified lines239 ext = list(env.iter_extensions())240 assert ext[0].__class__ is T1241 assert ext[1].__class__ is T2242 243+ def test_debug(self):244+ """Test for {% debug %}"""245+ env = Environment(extensions=['jinja2.ext.debug'])246+ tmpl = env.from_string('''Hello{% debug %}Bye''')247+ out = tmpl.render()248+ out = out.replace(''', "'").replace('<', '<').replace('>', '>')249+ #250+ # Check that some of the built-in items exist in the debug output...251+ #252+ assert "'context'" in out253+ assert "'cycler'" in out254+ assert "'filters'" in out255+ assert "'abs'" in out256+ assert "'tests'" in out257+ assert "'!='" in out258 259+260 @pytest.mark.ext261 class TestInternationalization(object):262 263 def test_trans(self):341 unmodified lines