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
Provenance
- Commit
3ea88fe- Tree
865f6c3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
496c81a- Parent 2
5e645ab
5 files changed+130 added−33 removed
modified:docs/extensions.rst+42 added-30 removed
12 unmodified lines13 14 Extensions are added to the Jinja2 environment at creation time. Once the15 environment is created additional extensions cannot be added. To add an16 extension 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 following18 example creates a Jinja2 environment with the i18n extension loaded::19 20 jinja_env = Environment(extensions=['jinja2.ext.i18n'])21 2 unmodified lines24 25 i18n Extension26 --------------27 28-**Import name:** `jinja2.ext.i18n`28+**Import name:** ``jinja2.ext.i18n``29 30 The i18n extension can be used in combination with `gettext`_ or `babel`_. If31-the i18n extension is enabled Jinja2 provides a `trans` statement that marks32-the wrapped string as translatable and calls `gettext`.31+the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32+the wrapped string as translatable and calls ``gettext``.33 34-After enabling, dummy `_` function that forwards calls to `gettext` is added34+After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35 to the environment globals. An internationalized application then has to36-provide a `gettext` function and optionally an `ngettext` function into the36+provide a ``gettext`` function and optionally an ``ngettext`` function into the37 namespace, either globally or for each rendering.38 39 Environment Methods40 ~~~~~~~~~~~~~~~~~~~3 unmodified lines44 45 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)46 47 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.51 52 .. versionchanged:: 2.5 newstyle gettext added53 54 .. method:: jinja2.Environment.install_null_translations(newstyle=False)5 unmodified lines60 .. versionchanged:: 2.5 newstyle gettext added61 62 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)63 64- 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.68 69- 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.71 72 .. versionadded:: 2.573 7 unmodified lines81 82 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:84 85- * `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).90 91 If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92 can be used to extract strings for babel.93 5 unmodified lines99 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])101 env.install_gettext_translations(translations)102 103-The `get_gettext_translations` function would return the translator for the104-current configuration. (For example by using `gettext.find`)103+The ``get_gettext_translations`` function would return the translator for the104+current configuration. (For example by using ``gettext.find``)105 106-The usage of the `i18n` extension for template designers is covered as part106+The usage of the ``i18n`` extension for template designers is covered as part107 :ref:`of the template documentation <i18n-in-templates>`.108 109 .. _gettext: https://docs.python.org/3/library/gettext.html110 .. _Babel: http://babel.pocoo.org/56 unmodified lines167 168 Expression Statement169 --------------------170 171-**Import name:** `jinja2.ext.do`171+**Import name:** ``jinja2.ext.do``172 173-The "do" aka expression-statement extension adds a simple `do` tag to the173+The "do" aka expression-statement extension adds a simple ``do`` tag to the174 template engine that works like a variable expression but ignores the175 return value.176 177 .. _loopcontrols-extension:178 179 Loop Controls180 -------------181 182-**Import name:** `jinja2.ext.loopcontrols`182+**Import name:** ``jinja2.ext.loopcontrols``183 184-This extension adds support for `break` and `continue` in loops. After184+This extension adds support for ``break`` and ``continue`` in loops. After185 enabling, Jinja2 provides those two keywords which work exactly like in186 Python.187 188 .. _with-extension:189 190 With Statement191 --------------192 193-**Import name:** `jinja2.ext.with_`193+**Import name:** ``jinja2.ext.with_``194 195 .. versionchanged:: 2.9196 197-This extension is now built-in and no longer does anything.197+ This extension is now built-in and no longer does anything.198 199 .. _autoescape-extension:200 201 Autoescape Extension202 --------------------203 204-**Import name:** `jinja2.ext.autoescape`204+**Import name:** ``jinja2.ext.autoescape``205 206 .. versionchanged:: 2.9207 208-This extension was removed and is now built-in. Enabling the extension209-no longer does anything.208+ This extension was removed and is now built-in. Enabling the209+ extension no longer does anything.210 211 212+.. _debug-extension:213+214+Debug Extension215+---------------216+217+**Import name:** ``jinja2.ext.debug``218+219+Adds a ``{% debug %}`` tag to dump the current context as well as the220+available filters and tests. This is useful to see what's available to221+use in the template without setting up a debugger.222+223+224 .. _writing-extensions:225 226 Writing Extensions227 ------------------14 unmodified lines242 243 Example Extension244 ~~~~~~~~~~~~~~~~~245 234-The following example implements a `cache` tag for Jinja2 by using the246+The following example implements a ``cache`` tag for Jinja2 by using the247 `cachelib`_ library:248 249 .. literalinclude:: cache_extension.py250 :language: python52 unmodified lines303 304 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``.308 309 .. attribute:: name310 311 The load name of the template.18 unmodified lines330 331 .. attribute:: type332 333 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.335 336 .. attribute:: value337 338 The value of the token.24 unmodified linesmodified:docs/templates.rst+23 added
1656 unmodified lines1657 Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 01658 (See: :ref:`for-loop`).1659 1660 1661+Debug Statement1662+~~~~~~~~~~~~~~~1663+1664+If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be1665+available to dump the current context as well as the available filters1666+and tests. This is useful to see what's available to use in the template1667+without setting up a debugger.1668+1669+.. code-block:: html+jinja1670+1671+ <pre>{% debug %}</pre>1672+1673+.. code-block:: text1674+1675+ {'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']}1682+1683+1684 With Statement1685 ~~~~~~~~~~~~~~1686 1687 .. versionadded:: 2.374 unmodified linesmodified:jinja2/ext.py+54 added-3 removed
1 unmodified line2 """3 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.6+ Jinja extensions allow adding custom tags and behavior. The7+ following extensions are included:8 9+ - An 18n support ``{% trans %}`` tag.10+ - A ``{% do %}`` tag.11+ - Loop control ``{% break %}`` and ``{% continue %}`` tags.12+ - A ``{% debug %}`` tag.13+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+ """A ``{% debug %}`` tag that dumps the available variables,447+ filters, and tests.448+449+ .. code-block:: html+jinja450+451+ <pre>{% debug %}</pre>452+453+ .. code-block:: text454+455+ {'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']}462+463+ .. versionadded:: 2.11.0464+ """465+ tags = {'debug'}466+467+ 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)472+473+ 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+ }479+480+ # 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)485+486+487 def 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 string183 unmodified lines674 do = ExprStmtExtension675 loopcontrols = LoopControlExtension676 with_ = WithExtension677 autoescape = AutoEscapeExtension678+debug = DebugExtensionmodified:tests/test_ext.py+8 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+ env = Environment(extensions=['jinja2.ext.debug'])245+ t = env.from_string('Hello\n{% debug %}\nGoodbye')246+ out = t.render()247 248+ for value in ("context", "cycler", "filters", "abs", "tests", "!="):249+ assert "'{}'".format(value) in out250+251+252 @pytest.mark.ext253 class TestInternationalization(object):254 255 def test_trans(self):341 unmodified linesmodified:CHANGES.rst+3 added
22 unmodified lines23 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`30 31 32 Version 2.10.333 --------------629 unmodified lines