Skip to content
Myr

Merge pull request #983 from kevin-brown/pr/798

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add support for a {% debug %} extension tag.

authored by David Lord · committed by GitHub · parents 496c81a, 5e645ab · Browse files · 5 files+130 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+130 added−33 removed

  • tests:+8 added−0 removed
  • other:+122 added−33 removed

5 files+130 added−33 removed

modified:docs/extensions.rst+42 added-30 removed
12 unmodified lines
1314Extensions are added to the Jinja2 environment at creation time. Once the15environment is created additional extensions cannot be added. To add an16extension pass a list of extension classes or import paths to the17`extensions` parameter of the :class:`Environment` constructor. The following17``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following18example creates a Jinja2 environment with the i18n extension loaded::1920 jinja_env = Environment(extensions=['jinja2.ext.i18n'])21
2 unmodified lines
2425i18n Extension26--------------2728**Import name:** `jinja2.ext.i18n`28**Import name:** ``jinja2.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or `babel`_. If31the i18n extension is enabled Jinja2 provides a `trans` statement that marks32the wrapped string as translatable and calls `gettext`.31the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32the wrapped string as translatable and calls ``gettext``.3334After enabling, dummy `_` function that forwards calls to `gettext` is added34After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35to the environment globals. An internationalized application then has to36provide a `gettext` function and optionally an `ngettext` function into the36provide a ``gettext`` function and optionally an ``ngettext`` function into the37namespace, either globally or for each rendering.3839Environment Methods40~~~~~~~~~~~~~~~~~~~
3 unmodified lines
4445.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4647 Installs a translation globally for that environment. The translations48 object provided must implement at least `ugettext` and `ungettext`.49 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes50 as well as `Babel`_\s `Translations` class are supported.48 object provided must implement at least ``ugettext`` and ``ungettext``.49 The ``gettext.NullTranslations`` and ``gettext.GNUTranslations`` classes50 as well as `Babel`_\s ``Translations`` class are supported.5152 .. versionchanged:: 2.5 newstyle gettext added5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)
5 unmodified lines
60 .. versionchanged:: 2.5 newstyle gettext added6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 Installs the given `gettext` and `ngettext` callables into the64 Installs the given ``gettext`` and ``ngettext`` callables into the65 environment as globals. They are supposed to behave exactly like the66 standard library's :func:`gettext.ugettext` and67 :func:`gettext.ungettext` functions.6869 If `newstyle` is activated, the callables are wrapped to work like69 If ``newstyle`` is activated, the callables are wrapped to work like70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.573
7 unmodified lines
8182 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:8485 * `lineno` is the number of the line on which the string was found,86 * `function` is the name of the `gettext` function used (if the85 * ``lineno`` is the number of the line on which the string was found,86 * ``function`` is the name of the ``gettext`` function used (if the87 string was extracted from embedded Python code), and88 * `message` is the string itself (a `unicode` object, or a tuple89 of `unicode` objects for functions with multiple string arguments).88 * ``message`` is the string itself (a ``unicode`` object, or a tuple89 of ``unicode`` objects for functions with multiple string arguments).9091 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92 can be used to extract strings for babel.93
5 unmodified lines
99 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])101 env.install_gettext_translations(translations)102103The `get_gettext_translations` function would return the translator for the104current configuration. (For example by using `gettext.find`)103The ``get_gettext_translations`` function would return the translator for the104current configuration. (For example by using ``gettext.find``)105106The usage of the `i18n` extension for template designers is covered as part106The usage of the ``i18n`` extension for template designers is covered as part107:ref:`of the template documentation <i18n-in-templates>`.108109.. _gettext: https://docs.python.org/3/library/gettext.html110.. _Babel: http://babel.pocoo.org/
56 unmodified lines
167168Expression Statement169--------------------170171**Import name:** `jinja2.ext.do`171**Import name:** ``jinja2.ext.do``172173The "do" aka expression-statement extension adds a simple `do` tag to the173The "do" aka expression-statement extension adds a simple ``do`` tag to the174template engine that works like a variable expression but ignores the175return value.176177.. _loopcontrols-extension:178179Loop Controls180-------------181182**Import name:** `jinja2.ext.loopcontrols`182**Import name:** ``jinja2.ext.loopcontrols``183184This extension adds support for `break` and `continue` in loops. After184This extension adds support for ``break`` and ``continue`` in loops. After185enabling, Jinja2 provides those two keywords which work exactly like in186Python.187188.. _with-extension:189190With Statement191--------------192193**Import name:** `jinja2.ext.with_`193**Import name:** ``jinja2.ext.with_``194195.. versionchanged:: 2.9196197This extension is now built-in and no longer does anything.197 This extension is now built-in and no longer does anything.198199.. _autoescape-extension:200201Autoescape Extension202--------------------203204**Import name:** `jinja2.ext.autoescape`204**Import name:** ``jinja2.ext.autoescape``205206.. versionchanged:: 2.9207208This extension was removed and is now built-in. Enabling the extension209no longer does anything.208 This extension was removed and is now built-in. Enabling the209 extension no longer does anything.210211212.. _debug-extension:213214Debug Extension215---------------216217**Import name:** ``jinja2.ext.debug``218219Adds a ``{% debug %}`` tag to dump the current context as well as the220available filters and tests. This is useful to see what's available to221use in the template without setting up a debugger.222223224.. _writing-extensions:225226Writing Extensions227------------------
14 unmodified lines
242243Example Extension244~~~~~~~~~~~~~~~~~245234The following example implements a `cache` tag for Jinja2 by using the246The following example implements a ``cache`` tag for Jinja2 by using the247`cachelib`_ library:248249.. literalinclude:: cache_extension.py250 :language: python
52 unmodified lines
303304 The filename of the template the parser processes. This is **not**305 the load name of the template. For the load name see :attr:`name`.306 For templates that were not loaded form the file system this is295 `None`.307 ``None``.308309 .. attribute:: name310311 The load name of the template.
18 unmodified lines
330331 .. attribute:: type332333 The type of the token. This string is interned so you may compare322 it with arbitrary strings using the `is` operator.334 it with arbitrary strings using the ``is`` operator.335336 .. attribute:: value337338 The value of the token.
24 unmodified lines
modified:docs/templates.rst+23 added
1656 unmodified lines
1657Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 01658(See: :ref:`for-loop`).165916601661Debug Statement1662~~~~~~~~~~~~~~~16631664If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be1665available to dump the current context as well as the available filters1666and tests. This is useful to see what's available to use in the template1667without setting up a debugger.16681669.. code-block:: html+jinja16701671 <pre>{% debug %}</pre>16721673.. code-block:: text16741675 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,1676 ...,1677 'namespace': <class 'jinja2.utils.Namespace'>},1678 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',1679 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],1680 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',1681 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}168216831684With Statement1685~~~~~~~~~~~~~~16861687.. versionadded:: 2.3
74 unmodified lines
modified:jinja2/ext.py+54 added-3 removed
1 unmodified line
2"""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.6 Jinja extensions allow adding custom tags and behavior. The7 following extensions are included:89 - An 18n support ``{% trans %}`` tag.10 - A ``{% do %}`` tag.11 - Loop control ``{% break %}`` and ``{% continue %}`` tags.12 - A ``{% debug %}`` tag.1314 :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 """A ``{% debug %}`` tag that dumps the available variables,447 filters, and tests.448449 .. code-block:: html+jinja450451 <pre>{% debug %}</pre>452453 .. code-block:: text454455 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,456 ...,457 'namespace': <class 'jinja2.utils.Namespace'>},458 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',459 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],460 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',461 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}462463 .. versionadded:: 2.11.0464 """465 tags = {'debug'}466467 def parse(self, parser):468 lineno = parser.stream.expect("name:debug").lineno469 context = ContextReference()470 result = self.call_method("_render", [context], lineno=lineno)471 return nodes.Output([result], lineno=lineno)472473 def _render(self, context):474 result = {475 "context": context.get_all(),476 "filters": sorted(self.environment.filters.keys()),477 "tests": sorted(self.environment.tests.keys()),478 }479480 # Set the depth since the intent is to show the top few names.481 if version_info[:2] >= (3, 4):482 return pprint.pformat(result, depth=3, compact=True)483 else:484 return pprint.pformat(result, depth=3)485486487def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,488 babel_style=True):489 """Extract localizable strings from the given template node. Per490 default this function returns matches in babel style that means non string
183 unmodified lines
674do = ExprStmtExtension675loopcontrols = LoopControlExtension676with_ = WithExtension677autoescape = AutoEscapeExtension678debug = DebugExtension
modified:tests/test_ext.py+8 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 env = Environment(extensions=['jinja2.ext.debug'])245 t = env.from_string('Hello\n{% debug %}\nGoodbye')246 out = t.render()247248 for value in ("context", "cycler", "filters", "abs", "tests", "!="):249 assert "'{}'".format(value) in out250251252@pytest.mark.ext253class TestInternationalization(object):254255 def test_trans(self):
341 unmodified lines
modified:CHANGES.rst+3 added
22 unmodified lines
23 legibility, like 12_345. :pr:`923`24- Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`25- The ``trim`` filter takes an optional string of characters to trim.26 :pr:`828`27- A new ``jinja2.ext.debug`` extension adds a ``{% debug %}`` tag to28 quickly dump the current context and available filters and tests.29 :issue:`174`, :pr:`798, 983`303132Version 2.10.333--------------
629 unmodified lines