Jinja2 uses a central object called the template :class:`Environment`.
Instances of this class are used to store the configuration, global objects
and are used to load templates from the file system or other locations.
-Even if you are creating templates from string by using the constructor of
+Even if you are creating templates from strings by using the constructor of
:class:`Template` class, an environment is created automatically for you,
albeit a shared one.
Unicode
-------
-Jinja2 is using unicode internally which means that you have to pass unicode
+Jinja2 is using Unicode internally which means that you have to pass Unicode
objects to the render function or bytestrings that only consist of ASCII
characters. Additionally newlines are normalized to one end of line
sequence which is per default UNIX style (``\n``).
`str` type and the other is the `unicode` type, both of which extend a type
called `basestring`. Unfortunately the default is `str` which should not
be used to store text based information unless only ASCII characters are
-used. With Python 2.6 it is possible to my `unicode` the default on a per
+used. With Python 2.6 it is possible to make `unicode` the default on a per
module level and with Python 3 it will be the default.
-To explicitly use a unicode string you have to prefix the string literal
+To explicitly use a Unicode string you have to prefix the string literal
with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will
-store the string as unicode by decoding the string with the character
+store the string as Unicode by decoding the string with the character
encoding from the current Python module. If no encoding is specified this
defaults to 'ASCII' which means that you can't use any non ASCII identifier.
To set a better module encoding add the following comment to the first or
-second line of the Python module using the unicode literal::
+second line of the Python module using the Unicode literal::
# -*- coding: utf-8 -*-
backwards compatible to ASCII. For Jinja2 the default encoding of templates
is assumed to be utf-8.
-It is not possible to use Jinja2 to process non unicode data. The reason
+It is not possible to use Jinja2 to process non-Unicode data. The reason
for this is that Jinja2 uses Unicode already on the language level. For
example Jinja2 treats the non-breaking space as valid whitespace inside
expressions which requires knowledge of the encoding or operating on an
-unicode string.
+Unicode string.
-For more details about unicode in Python have a look at the excellent
+For more details about Unicode in Python have a look at the excellent
`Unicode documentation`_.
Another important thing is how Jinja2 is handling string literals in
-templates. A naive implementation would be using unicode strings for
+templates. A naive implementation would be using Unicode strings for
all string literals but it turned out in the past that this is problematic
as some libraries are typechecking against `str` explicitly. For example
-`datetime.strftime` does not accept unicode arguments. To not break it
+`datetime.strftime` does not accept Unicode arguments. To not break it
completely Jinja2 is returning `str` for strings that fit into ASCII and
for everything else `unicode`:
<jinja-extensions>`.
.. autoclass:: Environment([options])
- :members: from_string, get_template, join_path, extend
+ :members: from_string, get_template, select_template,
+ get_or_select_template, join_path, extend, compile_expression
.. attribute:: shared
some operations. All parameters except of `hint` should be provided
as keyword parameters for better readability. The `hint` is used as
error message for the exception if provided, otherwise the error
- message generated from `obj` and `name` automatically. The exception
+ message will be generated from `obj` and `name` automatically. The exception
provided as `exc` is raised if something with the generated undefined
object is done that the undefined object does not allow. The default
exception is :exc:`UndefinedError`. If a `hint` is provided the
:members: disable_buffering, enable_buffering, dump
+Autoescaping
+------------
+
+.. versionadded:: 2.4
+
+As of Jinja 2.4 the preferred way to do autoescaping is to enable the
+:ref:`autoescape-extension` and to configure a sensible default for
+autoescaping. This makes it possible to enable and disable autoescaping
+on a per-template basis (HTML versus text for instance).
+
+Here a recommended setup that enables autoescaping for templates ending
+in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default
+for all other extensions::
+
+ def guess_autoescape(template_name):
+ if template_name is None or '.' not in template_name:
+ return False
+ ext = template_name.rsplit('.', 1)[1]
+ return ext in ('html', 'htm', 'xml')
+
+ env = Environment(autoescape=guess_autoescape,
+ loader=PackageLoader('mypackage'),
+ extensions=['jinja2.ext.autoescape'])
+
+When implementing a guessing autoescape function, make sure you also
+accept `None` as valid template name. This will be passed when generating
+templates from strings.
+
+Inside the templates the behaviour can be temporarily changed by using
+the `autoescape` block (see :ref:`autoescape-overrides`).
+
+
.. _identifier-naming:
Notes on Identifiers
The closest to regular Python behavior is the `StrictUndefined` which
disallows all operations beside testing if it's an undefined object.
-.. autoclass:: jinja2.runtime.Undefined()
+.. autoclass:: jinja2.Undefined()
.. attribute:: _undefined_hint
:attr:`_undefined_exception` with an error message generated
from the undefined hints stored on the undefined object.
-.. autoclass:: jinja2.runtime.DebugUndefined()
+.. autoclass:: jinja2.DebugUndefined()
-.. autoclass:: jinja2.runtime.StrictUndefined()
+.. autoclass:: jinja2.StrictUndefined()
Undefined objects are created by calling :attr:`undefined`.
blocks registered. The last item in each list is the current active
block (latest in the inheritance chain).
+ .. attribute:: eval_ctx
+
+ The current :ref:`eval-context`.
+
.. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
All loaders are subclasses of :class:`BaseLoader`. If you want to create your
own loader, subclass :class:`BaseLoader` and override `get_source`.
-.. autoclass:: jinja2.loaders.BaseLoader
+.. autoclass:: jinja2.BaseLoader
:members: get_source, load
Here a list of the builtin loaders Jinja2 provides:
-.. autoclass:: jinja2.loaders.FileSystemLoader
+.. autoclass:: jinja2.FileSystemLoader
+
+.. autoclass:: jinja2.PackageLoader
-.. autoclass:: jinja2.loaders.PackageLoader
+.. autoclass:: jinja2.DictLoader
-.. autoclass:: jinja2.loaders.DictLoader
+.. autoclass:: jinja2.FunctionLoader
-.. autoclass:: jinja2.loaders.FunctionLoader
+.. autoclass:: jinja2.PrefixLoader
-.. autoclass:: jinja2.loaders.PrefixLoader
+.. autoclass:: jinja2.ChoiceLoader
+
+
+.. _bytecode-cache:
+
+Bytecode Cache
+--------------
-.. autoclass:: jinja2.loaders.ChoiceLoader
+Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
+it possible to store the generated bytecode on the file system or a different
+location to avoid parsing the templates on first use.
+
+This is especially useful if you have a web application that is initialized on
+the first request and Jinja compiles many templates at once which slows down
+the application.
+
+To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.
+
+.. autoclass:: jinja2.BytecodeCache
+ :members: load_bytecode, dump_bytecode, clear
+
+.. autoclass:: jinja2.bccache.Bucket
+ :members: write_bytecode, load_bytecode, bytecode_from_string,
+ bytecode_to_string, reset
+
+ .. attribute:: environment
+
+ The :class:`Environment` that created the bucket.
+
+ .. attribute:: key
+
+ The unique cache key for this bucket
+
+ .. attribute:: code
+
+ The bytecode if it's loaded, otherwise `None`.
+
+
+Builtin bytecode caches:
+
+.. autoclass:: jinja2.FileSystemBytecodeCache
+
+.. autoclass:: jinja2.MemcachedBytecodeCache
Utilities
These helper functions and classes are useful if you add custom filters or
functions to a Jinja2 environment.
-.. autofunction:: jinja2.filters.environmentfilter
+.. autofunction:: jinja2.environmentfilter
+
+.. autofunction:: jinja2.contextfilter
-.. autofunction:: jinja2.filters.contextfilter
+.. autofunction:: jinja2.evalcontextfilter
-.. autofunction:: jinja2.utils.environmentfunction
+.. autofunction:: jinja2.environmentfunction
-.. autofunction:: jinja2.utils.contextfunction
+.. autofunction:: jinja2.contextfunction
+
+.. autofunction:: jinja2.evalcontextfunction
.. function:: escape(s)
The return value is a :class:`Markup` string.
-.. autofunction:: jinja2.utils.clear_caches
+.. autofunction:: jinja2.clear_caches
-.. autofunction:: jinja2.utils.is_undefined
+.. autofunction:: jinja2.is_undefined
-.. autoclass:: jinja2.utils.Markup([string])
+.. autoclass:: jinja2.Markup([string])
:members: escape, unescape, striptags
.. admonition:: Note
Exceptions
----------
-.. autoexception:: jinja2.exceptions.TemplateError
+.. autoexception:: jinja2.TemplateError
+
+.. autoexception:: jinja2.UndefinedError
-.. autoexception:: jinja2.exceptions.UndefinedError
+.. autoexception:: jinja2.TemplateNotFound
-.. autoexception:: jinja2.exceptions.TemplateNotFound
+.. autoexception:: jinja2.TemplatesNotFound
-.. autoexception:: jinja2.exceptions.TemplateSyntaxError
+.. autoexception:: jinja2.TemplateSyntaxError
.. attribute:: message
unicode strings is that Python 2.x is not using unicode for exceptions
and tracebacks as well as the compiler. This will change with Python 3.
-.. autoexception:: jinja2.exceptions.TemplateAssertionError
+.. autoexception:: jinja2.TemplateAssertionError
.. _writing-filters:
publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
Filters can also be passed the current template context or environment. This
-is useful if a filters wants to return an undefined value or check the current
+is useful if a filter wants to return an undefined value or check the current
:attr:`~Environment.autoescape` setting. For this purpose two decorators
-exist: :func:`environmentfilter` and :func:`contextfilter`.
+exist: :func:`environmentfilter`, :func:`contextfilter` and
+:func:`evalcontextfilter`.
Here a small example filter that breaks a text into HTML line breaks and
paragraphs and marks the return value as safe HTML string if autoescaping is
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
- @environmentfilter
- def nl2br(environment, value):
+ @evalcontextfilter
+ def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
for p in _paragraph_re.split(escape(value)))
- if environment.autoescape:
+ if eval_ctx.autoescape:
result = Markup(result)
return result
active :class:`Context` rather then the environment.
+.. _eval-context:
+
+Evaluation Context
+------------------
+
+The evaluation context (short eval context or eval ctx) is a new object
+introducted in Jinja 2.4 that makes it possible to activate and deactivate
+compiled features at runtime.
+
+Currently it is only used to enable and disable the automatic escaping but
+can be used for extensions as well.
+
+In previous Jinja versions filters and functions were marked as
+environment callables in order to check for the autoescape status from the
+environment. In new versions it's encouraged to check the setting from the
+evaluation context instead.
+
+Previous versions::
+
+ @environmentfilter
+ def filter(env, value):
+ result = do_something(value)
+ if env.autoescape:
+ result = Markup(result)
+ return result
+
+In new versions you can either use a :func:`contextfilter` and access the
+evaluation context from the actual context, or use a
+:func:`evalcontextfilter` which directly passes the evaluation context to
+the function::
+
+ @contextfilter
+ def filter(context, value):
+ result = do_something(value)
+ if context.eval_ctx.autoescape:
+ result = Markup(result)
+ return result
+
+ @evalcontextfilter
+ def filter(eval_ctx, value):
+ result = do_something(value)
+ if eval_ctx.autoescape:
+ result = Markup(result)
+ return result
+
+The evaluation context must not be modified at runtime. Modifications
+must only happen with a :class:`nodes.EvalContextModifier` and
+:class:`nodes.ScopedEvalContextModifier` from an extension, not on the
+eval context object itself.
+
+.. autoclass:: jinja2.nodes.EvalContext
+
+ .. attribute:: autoescape
+
+ `True` or `False` depending on if autoescaping is active or not.
+
+ .. attribute:: volatile
+
+ `True` if the compiler cannot evaluate some expressions at compile
+ time. At runtime this should always be `False`.
+
+
.. _writing-tests:
Custom Tests
------------
-Tests work like filters just that there is no way for a filter to get access
+Tests work like filters just that there is no way for a test to get access
to the environment or context and that they can't be chained. The return
-value of a filter should be `True` or `False`. The purpose of a filter is to
+value of a test should be `True` or `False`. The purpose of a test is to
give the template designers the possibility to perform type and conformability
checks.
-Here a simple filter that checks if a variable is a prime number::
+Here a simple test that checks if a variable is a prime number::
import math
change it in a backwards incompatible way but modifications in the Jinja2
core may shine through. For example if Jinja2 introduces a new AST node
in later versions that may be returned by :meth:`~Environment.parse`.
+
+The Meta API
+------------
+
+.. versionadded:: 2.2
+
+The meta API returns some information about abstract syntax trees that
+could help applications to implement more advanced template concepts. All
+the functions of the meta API operate on an abstract syntax tree as
+returned by the :meth:`Environment.parse` method.
+
+.. autofunction:: jinja2.meta.find_undeclared_variables
+
+.. autofunction:: jinja2.meta.find_referenced_templates