Skip to content
Myr

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

2 files+80 added−2 removed

modified:jinja2/ext.py+64 added-2 removed
2 unmodified lines
3 jinja2.ext4 ~~~~~~~~~~56 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:89 - a i18n support {% trans %} tag10 - a {% do %} tag11 - loop control {% break %} and {% continue %} tags12 - a {% debug %} tag1314 :copyright: (c) 2017 by the Jinja Team.15 :license: BSD.16"""17import pprint18import re19from sys import version_info2021from jinja2 import nodes22from 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_BLOCKS27from jinja2.environment import Environment28from jinja2.nodes import ContextReference29from jinja2.runtime import concat30from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError31from jinja2.utils import contextfunction, import_string, Markup32from jinja2._compat import with_metaclass, string_types, iteritems33from markupsafe import escape343536# the only real useful gettext functions for a Jinja template. Note37# that ugettext must be assigned to gettext as Jinja doesn't support
403 unmodified lines
441class AutoEscapeExtension(Extension):442 pass443444445class DebugExtension(Extension):446 """447 A ``{% debug %}`` tag that dumps the available variables, filters and tests.448 Typical usage like this:449450 .. codeblock:: html+jinja451 <pre>{% debug %}</pre>452453 produces output like this:454455 ::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']}467468 """469 tags = {'debug'}470471 def __init__(self, environment):472 super(DebugExtension, self).__init__(environment)473474 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)])479480 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 text496497498def 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 string
183 unmodified lines
685do = ExprStmtExtension686loopcontrols = LoopControlExtension687with_ = WithExtension688autoescape = AutoEscapeExtension689debug = DebugExtension
modified:tests/test_ext.py+16 added
238 unmodified lines
239 ext = list(env.iter_extensions())240 assert ext[0].__class__ is T1241 assert ext[1].__class__ is T2242243 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('&#39;', "'").replace('&lt;', '<').replace('&gt;', '>')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 out258259260@pytest.mark.ext261class TestInternationalization(object):262263 def test_trans(self):
341 unmodified lines