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'])
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
.. 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
.. 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
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.
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
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.
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.
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:
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
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
.. 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
(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
~~~~~~~~~~~~~~
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.
"""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.