]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
document debug extension 983/head
authorDavid Lord <davidism@gmail.com>
Sat, 5 Oct 2019 02:00:11 +0000 (19:00 -0700)
committerDavid Lord <davidism@gmail.com>
Sat, 5 Oct 2019 02:13:39 +0000 (19:13 -0700)
CHANGES.rst
docs/extensions.rst
docs/templates.rst
jinja2/ext.py

index 54427d8c197773ad566494f7910225a1b384e3b8..28b4579ebe0572fff6361b52a859244f5baba427 100644 (file)
@@ -24,6 +24,9 @@ Unreleased
 -   Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`
 -   The ``trim`` filter takes an optional string of characters to trim.
     :pr:`828`
+-   A new ``jinja2.ext.debug`` extension adds a ``{% debug %}`` tag to
+    quickly dump the current context and available filters and tests.
+    :issue:`174`, :pr:`798, 983`
 
 
 Version 2.10.3
index 12c589076b097bffa852571a9e041436731c3418..b21b111332d3e5f6e93aa8ca2adfb9b09b75122d 100644 (file)
@@ -14,7 +14,7 @@ Adding Extensions
 Extensions are added to the Jinja2 environment at creation time.  Once the
 environment is created additional extensions cannot be added.  To add an
 extension pass a list of extension classes or import paths to the
-`extensions` parameter of the :class:`Environment` constructor.  The following
+``extensions`` parameter of the :class:`~jinja2.Environment` constructor.  The following
 example creates a Jinja2 environment with the i18n extension loaded::
 
     jinja_env = Environment(extensions=['jinja2.ext.i18n'])
@@ -25,15 +25,15 @@ example creates a Jinja2 environment with the i18n extension loaded::
 i18n Extension
 --------------
 
-**Import name:** `jinja2.ext.i18n`
+**Import name:** ``jinja2.ext.i18n``
 
 The i18n extension can be used in combination with `gettext`_ or `babel`_.  If
-the i18n extension is enabled Jinja2 provides a `trans` statement that marks
-the wrapped string as translatable and calls `gettext`.
+the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks
+the wrapped string as translatable and calls ``gettext``.
 
-After enabling, dummy `_` function that forwards calls to `gettext` is added
+After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added
 to the environment globals.  An internationalized application then has to
-provide a `gettext` function and optionally an `ngettext` function into the
+provide a ``gettext`` function and optionally an ``ngettext`` function into the
 namespace, either globally or for each rendering.
 
 Environment Methods
@@ -45,9 +45,9 @@ additional methods:
 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)
 
     Installs a translation globally for that environment.  The translations
-    object provided must implement at least `ugettext` and `ungettext`.
-    The `gettext.NullTranslations` and `gettext.GNUTranslations` classes
-    as well as `Babel`_\s `Translations` class are supported.
+    object provided must implement at least ``ugettext`` and ``ungettext``.
+    The ``gettext.NullTranslations`` and ``gettext.GNUTranslations`` classes
+    as well as `Babel`_\s ``Translations`` class are supported.
 
     .. versionchanged:: 2.5 newstyle gettext added
 
@@ -61,12 +61,12 @@ additional methods:
 
 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)
 
-    Installs the given `gettext` and `ngettext` callables into the
+    Installs the given ``gettext`` and ``ngettext`` callables into the
     environment as globals.  They are supposed to behave exactly like the
     standard library's :func:`gettext.ugettext` and
     :func:`gettext.ungettext` functions.
 
-    If `newstyle` is activated, the callables are wrapped to work like
+    If ``newstyle`` is activated, the callables are wrapped to work like
     newstyle callables.  See :ref:`newstyle-gettext` for more information.
 
     .. versionadded:: 2.5
@@ -82,11 +82,11 @@ additional methods:
     For every string found this function yields a ``(lineno, function,
     message)`` tuple, where:
 
-    * `lineno` is the number of the line on which the string was found,
-    * `function` is the name of the `gettext` function used (if the
+    * ``lineno`` is the number of the line on which the string was found,
+    * ``function`` is the name of the ``gettext`` function used (if the
       string was extracted from embedded Python code), and
-    *  `message` is the string itself (a `unicode` object, or a tuple
-       of `unicode` objects for functions with multiple string arguments).
+    *  ``message`` is the string itself (a ``unicode`` object, or a tuple
+       of ``unicode`` objects for functions with multiple string arguments).
 
     If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`
     can be used to extract strings for babel.
@@ -100,10 +100,10 @@ translation methods to the environment at environment generation time::
     env = Environment(extensions=['jinja2.ext.i18n'])
     env.install_gettext_translations(translations)
 
-The `get_gettext_translations` function would return the translator for the
-current configuration.  (For example by using `gettext.find`)
+The ``get_gettext_translations`` function would return the translator for the
+current configuration.  (For example by using ``gettext.find``)
 
-The usage of the `i18n` extension for template designers is covered as part
+The usage of the ``i18n`` extension for template designers is covered as part
 :ref:`of the template documentation <i18n-in-templates>`.
 
 .. _gettext: https://docs.python.org/3/library/gettext.html
@@ -168,9 +168,9 @@ templates are experiencing over time when using autoescaping.
 Expression Statement
 --------------------
 
-**Import name:** `jinja2.ext.do`
+**Import name:** ``jinja2.ext.do``
 
-The "do" aka expression-statement extension adds a simple `do` tag to the
+The "do" aka expression-statement extension adds a simple ``do`` tag to the
 template engine that works like a variable expression but ignores the
 return value.
 
@@ -179,9 +179,9 @@ return value.
 Loop Controls
 -------------
 
-**Import name:** `jinja2.ext.loopcontrols`
+**Import name:** ``jinja2.ext.loopcontrols``
 
-This extension adds support for `break` and `continue` in loops.  After
+This extension adds support for ``break`` and ``continue`` in loops.  After
 enabling, Jinja2 provides those two keywords which work exactly like in
 Python.
 
@@ -190,23 +190,35 @@ Python.
 With Statement
 --------------
 
-**Import name:** `jinja2.ext.with_`
+**Import name:** ``jinja2.ext.with_``
 
 .. versionchanged:: 2.9
 
-This extension is now built-in and no longer does anything.
+    This extension is now built-in and no longer does anything.
 
 .. _autoescape-extension:
 
 Autoescape Extension
 --------------------
 
-**Import name:** `jinja2.ext.autoescape`
+**Import name:** ``jinja2.ext.autoescape``
 
 .. versionchanged:: 2.9
 
-This extension was removed and is now built-in.  Enabling the extension
-no longer does anything.
+    This extension was removed and is now built-in. Enabling the
+    extension no longer does anything.
+
+
+.. _debug-extension:
+
+Debug Extension
+---------------
+
+**Import name:** ``jinja2.ext.debug``
+
+Adds a ``{% debug %}`` tag to dump the current context as well as the
+available filters and tests. This is useful to see what's available to
+use in the template without setting up a debugger.
 
 
 .. _writing-extensions:
@@ -231,7 +243,7 @@ how to use them.
 Example Extension
 ~~~~~~~~~~~~~~~~~
 
-The following example implements a `cache` tag for Jinja2 by using the
+The following example implements a ``cache`` tag for Jinja2 by using the
 `cachelib`_ library:
 
 .. literalinclude:: cache_extension.py
@@ -292,7 +304,7 @@ extensions:
         The filename of the template the parser processes.  This is **not**
         the load name of the template.  For the load name see :attr:`name`.
         For templates that were not loaded form the file system this is
-        `None`.
+        ``None``.
 
     .. attribute:: name
 
@@ -319,7 +331,7 @@ extensions:
     .. attribute:: type
 
         The type of the token.  This string is interned so you may compare
-        it with arbitrary strings using the `is` operator.
+        it with arbitrary strings using the ``is`` operator.
 
     .. attribute:: value
 
index 59a34dd34549b4e167b80444d5eac70b3d0cd8d5..f6fb609b2e2baf12fa6192a3d15e79adc723993d 100644 (file)
@@ -1658,6 +1658,29 @@ Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0
 (See: :ref:`for-loop`).
 
 
+Debug Statement
+~~~~~~~~~~~~~~~
+
+If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be
+available to dump the current context as well as the available filters
+and tests. This is useful to see what's available to use in the template
+without setting up a debugger.
+
+.. code-block:: html+jinja
+
+    <pre>{% debug %}</pre>
+
+.. code-block:: text
+
+    {'context': {'cycler': <class 'jinja2.utils.Cycler'>,
+                 ...,
+                 'namespace': <class 'jinja2.utils.Namespace'>},
+     'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',
+                 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],
+     'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',
+               ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
+
+
 With Statement
 ~~~~~~~~~~~~~~
 
index 2a29b1fdf8e7f7f27347c91030ba5079fd3dcb4c..8488e63f774a5c7673e105220dd6c53f25543893 100644 (file)
@@ -3,13 +3,13 @@
     jinja2.ext
     ~~~~~~~~~~
 
-    Jinja extensions allow to add custom tags similar to the way django custom
-    tags work.  The following default example extensions are included:
+    Jinja extensions allow adding custom tags and behavior. The
+    following extensions are included:
 
-        - a i18n support {% trans %} tag
-        - a {% do %} tag
-        - loop control {% break %} and {% continue %} tags
-        - a {% debug %} tag
+    -   An 18n support ``{% trans %}`` tag.
+    -   A ``{% do %}`` tag.
+    -   Loop control ``{% break %}`` and ``{% continue %}`` tags.
+    -   A ``{% debug %}`` tag.
 
     :copyright: (c) 2017 by the Jinja Team.
     :license: BSD.
@@ -446,42 +446,35 @@ class DebugExtension(Extension):
     """A ``{% debug %}`` tag that dumps the available variables,
     filters, and tests.
 
-    .. codeblock:: html+jinja
+    .. code-block:: html+jinja
 
         <pre>{% debug %}</pre>
 
-    .. code-block:: python
+    .. code-block:: text
 
-        {'context': {'_': <function _gettext_alias at 0x7f9ceabde488>,
-                 'csrf_token': <SimpleLazyObject: 'lfPE7al...q3bykS4txKfb3'>,
-                 'cycler': <class 'jinja2.utils.Cycler'>,
-                 ...
-                 'view': <polls.views_auth.Login object at 0x7f9cea2cbe48>},
-        'filters': ['abs', 'add', 'addslashes', 'attr', 'batch', 'bootstrap',
-                 'bootstrap_classes', 'bootstrap_horizontal',
-                 'bootstrap_inline', ... 'yesno'],
-        'tests': ['callable', 'checkbox_field', 'defined', 'divisibleby',
-               'escaped', 'even', 'iterable', 'lower', 'mapping',
-               'multiple_checkbox_field', ... 'string', 'undefined', 'upper']}
+        {'context': {'cycler': <class 'jinja2.utils.Cycler'>,
+                     ...,
+                     'namespace': <class 'jinja2.utils.Namespace'>},
+         'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',
+                     ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],
+         'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',
+                   ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
 
     .. versionadded:: 2.11.0
     """
     tags = {'debug'}
 
-    def __init__(self, environment):
-        super(DebugExtension, self).__init__(environment)
-
     def parse(self, parser):
-        lineno = parser.stream.expect('name:debug').lineno
+        lineno = parser.stream.expect("name:debug").lineno
         context = ContextReference()
-        result = self.call_method('_render', [context], lineno=lineno)
+        result = self.call_method("_render", [context], lineno=lineno)
         return nodes.Output([result], lineno=lineno)
 
     def _render(self, context):
         result = {
-            'filters': sorted(self.environment.filters.keys()),
-            'tests': sorted(self.environment.tests.keys()),
-            'context': context.get_all()
+            "context": context.get_all(),
+            "filters": sorted(self.environment.filters.keys()),
+            "tests": sorted(self.environment.tests.keys()),
         }
 
         # Set the depth since the intent is to show the top few names.