api.rst
This file
Path
docs/api.rst
935 lines · 32.2 KiB
Last changed by
Merge pull request #1161 from ldealmei/patch-1David Lordbefore adoptioneccf9a0
History of this fileTake it
The walk stopped after 200 commits: lines older than 793ddd4 point at it.
Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 1–3why, one step back1API2===3Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 4why, one step back4.. module:: jinja2Merge pull request #1015 from jab/pr-1011Joshua Bronsonbefore adoption7798e79
line 5why, one step back5 :noindex:Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 6why, one step back6 :synopsis: public Jinja APIMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 7why, one step back7Merge pull request #1161 from ldealmei/patch-1David Lordbefore adoptioneccf9a0
lines 8–11why, one step back8This document describes the API to Jinja and not the template language9(for that, see :doc:`/templates`). It will be most useful as reference10to those implementing the template interface to the application and not11those who are creating Jinja templates.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 12–15why, one step back1213Basics14------15Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 16why, one step back16Jinja uses a central object called the template :class:`Environment`.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 17–23why, one step back17Instances of this class are used to store the configuration and global objects,18and are used to load templates from the file system or other locations.19Even if you are creating templates from strings by using the constructor of20:class:`Template` class, an environment is created automatically for you,21albeit a shared one.2223Most applications will create one :class:`Environment` object on applicationMerge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207
line 24why, one step back24initialization and use that to load templates. In some cases however, it'sMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 25–27why, one step back25useful to have multiple environments side by side, if different configurations26are in use.27Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 28why, one step back28The simplest way to configure Jinja to load templates for your applicationMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 29–30why, one step back29looks roughly like this::30Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 31why, one step back31 from jinja2 import Environment, PackageLoader, select_autoescapeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 32–50why, one step back32 env = Environment(33 loader=PackageLoader('yourapplication', 'templates'),34 autoescape=select_autoescape(['html', 'xml'])35 )3637This will create a template environment with the default settings and a38loader that looks up the templates in the `templates` folder inside the39`yourapplication` python package. Different loaders are available40and you can also write your own if you want to load templates from a41database or other resources. This also enables autoescaping for HTML and42XML files.4344To load a template from this environment you just have to call the45:meth:`get_template` method which then returns the loaded :class:`Template`::4647 template = env.get_template('mytemplate.html')4849To render it with some variables, just call the :meth:`render` method::50Merge branch '2.10.x'David Lordbefore adoption13cc9f4
line 51why, one step back51 print(template.render(the='variables', go='here'))Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 52–58why, one step back5253Using a template loader rather than passing strings to :class:`Template`54or :meth:`Environment.from_string` has multiple advantages. Besides being55a lot easier to use it also enables template inheritance.5657.. admonition:: Notes on Autoescaping58Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 59why, one step back59 In future versions of Jinja we might enable autoescaping by defaultMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 60–66why, one step back60 for security reasons. As such you are encouraged to explicitly61 configure autoescaping now instead of relying on the default.626364Unicode65-------66Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 67why, one step back67Jinja is using Unicode internally which means that you have to pass UnicodeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 68–91why, one step back68objects to the render function or bytestrings that only consist of ASCII69characters. Additionally newlines are normalized to one end of line70sequence which is per default UNIX style (``\n``).7172Python 2.x supports two ways of representing string objects. One is the73`str` type and the other is the `unicode` type, both of which extend a type74called `basestring`. Unfortunately the default is `str` which should not75be used to store text based information unless only ASCII characters are76used. With Python 2.6 it is possible to make `unicode` the default on a per77module level and with Python 3 it will be the default.7879To explicitly use a Unicode string you have to prefix the string literal80with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will81store the string as Unicode by decoding the string with the character82encoding from the current Python module. If no encoding is specified this83defaults to 'ASCII' which means that you can't use any non ASCII identifier.8485To set a better module encoding add the following comment to the first or86second line of the Python module using the Unicode literal::8788 # -*- coding: utf-8 -*-8990We recommend utf-8 as Encoding for Python modules and templates as it's91possible to represent every Unicode character in utf-8 and because it'sMerge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 92why, one step back92backwards compatible to ASCII. For Jinja the default encoding of templatesMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 93–94why, one step back93is assumed to be utf-8.94Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
lines 95–97why, one step back95It is not possible to use Jinja to process non-Unicode data. The reason96for this is that Jinja uses Unicode already on the language level. For97example Jinja treats the non-breaking space as valid whitespace insideMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 98–103why, one step back98expressions which requires knowledge of the encoding or operating on an99Unicode string.100101For more details about Unicode in Python have a look at the excellent102`Unicode documentation`_.103Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 104why, one step back104Another important thing is how Jinja is handling string literals inMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 105–108why, one step back105templates. A naive implementation would be using Unicode strings for106all string literals but it turned out in the past that this is problematic107as some libraries are typechecking against `str` explicitly. For example108`datetime.strftime` does not accept Unicode arguments. To not break itMerge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 109why, one step back109completely Jinja is returning `str` for strings that fit into ASCII andMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 110–118why, one step back110for everything else `unicode`:111112>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module113>>> m.a114'foo'115>>> m.b116u'f\xf6\xf6'117118Merge branch '2.10.x'David Lordbefore adoption9550dc8
line 119why, one step back119.. _Unicode documentation: https://docs.python.org/3/howto/unicode.htmlMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 120–124why, one step back120121High Level API122--------------123124The high-level API is the API you will use in the application to load andMerge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
lines 125–126why, one step back125render Jinja templates. The :ref:`low-level-api` on the other side is only126useful if you want to dig deeper into Jinja or :ref:`develop extensionsMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 127–145why, one step back127<jinja-extensions>`.128129.. autoclass:: Environment([options])130 :members: from_string, get_template, select_template,131 get_or_select_template, join_path, extend, compile_expression,132 compile_templates, list_templates, add_extension133134 .. attribute:: shared135136 If a template was created by using the :class:`Template` constructor137 an environment is created automatically. These environments are138 created as shared environments which means that multiple templates139 may have the same anonymous environment. For all shared environments140 this attribute is `True`, else `False`.141142 .. attribute:: sandboxed143144 If the environment is sandboxed this attribute is `True`. For the145 sandbox mode have a look at the documentation for theMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 146why, one step back146 :class:`~jinja2.sandbox.SandboxedEnvironment`.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 147–185why, one step back147148 .. attribute:: filters149150 A dict of filters for this environment. As long as no template was151 loaded it's safe to add new filters or remove old. For custom filters152 see :ref:`writing-filters`. For valid filter names have a look at153 :ref:`identifier-naming`.154155 .. attribute:: tests156157 A dict of test functions for this environment. As long as no158 template was loaded it's safe to modify this dict. For custom tests159 see :ref:`writing-tests`. For valid test names have a look at160 :ref:`identifier-naming`.161162 .. attribute:: globals163164 A dict of global variables. These variables are always available165 in a template. As long as no template was loaded it's safe166 to modify this dict. For more details see :ref:`global-namespace`.167 For valid object names have a look at :ref:`identifier-naming`.168169 .. attribute:: policies170171 A dictionary with :ref:`policies`. These can be reconfigured to172 change the runtime behavior or certain template features. Usually173 these are security related.174175 .. attribute:: code_generator_class176177 The class used for code generation. This should not be changed178 in most cases, unless you need to modify the Python code a179 template compiles to.180181 .. attribute:: context_class182183 The context used for templates. This should not be changed184 in most cases, unless you need to modify internals of how185 template variables are handled. For details, seeMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 186why, one step back186 :class:`~jinja2.runtime.Context`.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 187–217why, one step back187188 .. automethod:: overlay([options])189190 .. method:: undefined([hint, obj, name, exc])191192 Creates a new :class:`Undefined` object for `name`. This is useful193 for filters or functions that may return undefined objects for194 some operations. All parameters except of `hint` should be provided195 as keyword parameters for better readability. The `hint` is used as196 error message for the exception if provided, otherwise the error197 message will be generated from `obj` and `name` automatically. The exception198 provided as `exc` is raised if something with the generated undefined199 object is done that the undefined object does not allow. The default200 exception is :exc:`UndefinedError`. If a `hint` is provided the201 `name` may be omitted.202203 The most common way to create an undefined object is by providing204 a name only::205206 return environment.undefined(name='some_name')207208 This means that the name `some_name` is not defined. If the name209 was from an attribute of an object it makes sense to tell the210 undefined object the holder object to improve the error message::211212 if not hasattr(obj, 'attr'):213 return environment.undefined(obj=obj, name='attr')214215 For a more complex example you can provide a hint. For example216 the :func:`first` filter creates an undefined object that way::217Merge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207
line 218why, one step back218 return environment.undefined('no first item, sequence was empty')Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 219–254why, one step back219220 If it the `name` or `obj` is known (for example because an attribute221 was accessed) it should be passed to the undefined object, even if222 a custom `hint` is provided. This gives undefined objects the223 possibility to enhance the error message.224225.. autoclass:: Template226 :members: module, make_module227228 .. attribute:: globals229230 The dict with the globals of that template. It's unsafe to modify231 this dict as it may be shared with other templates or the environment232 that loaded the template.233234 .. attribute:: name235236 The loading name of the template. If the template was loaded from a237 string this is `None`.238239 .. attribute:: filename240241 The filename of the template on the file system if it was loaded from242 there. Otherwise this is `None`.243244 .. automethod:: render([context])245246 .. automethod:: generate([context])247248 .. automethod:: stream([context])249250 .. automethod:: render_async([context])251252 .. automethod:: generate_async([context])253254Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 255why, one step back255.. autoclass:: jinja2.environment.TemplateStream()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 256–263why, one step back256 :members: disable_buffering, enable_buffering, dump257258259Autoescaping260------------261262.. versionchanged:: 2.4263Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 264why, one step back264Jinja now comes with autoescaping support. As of Jinja 2.9 theMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 265–270why, one step back265autoescape extension is removed and built-in. However autoescaping is266not yet enabled by default though this will most likely change in the267future. It's recommended to configure a sensible default for268autoescaping. This makes it possible to enable and disable autoescaping269on a per-template basis (HTML versus text for instance).270Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 271why, one step back271.. autofunction:: jinja2.select_autoescapeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 272–274why, one step back272273Here a recommended setup that enables autoescaping for templates ending274in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by defaultMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 275why, one step back275for all other extensions. You can use the :func:`~jinja2.select_autoescape`Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 276–277why, one step back276function for this::277Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 278why, one step back278 from jinja2 import Environment, select_autoescapeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 279–282why, one step back279 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),280 loader=PackageLoader('mypackage'))281282The :func:`~jinja.select_autoescape` function returns a function thatMerge pull request #783 from luzpaz/trivial-typosDavid Lordbefore adoption9b255f4
line 283why, one step back283works roughly like this::Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 284–303why, one step back284285 def autoescape(template_name):286 if template_name is None:287 return False288 if template_name.endswith(('.html', '.htm', '.xml'))289290When implementing a guessing autoescape function, make sure you also291accept `None` as valid template name. This will be passed when generating292templates from strings. You should always configure autoescaping as293defaults in the future might change.294295Inside the templates the behaviour can be temporarily changed by using296the `autoescape` block (see :ref:`autoescape-overrides`).297298299.. _identifier-naming:300301Notes on Identifiers302--------------------303Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
lines 304–305why, one step back304Jinja uses Python naming rules. Valid identifiers can be any combination305of Unicode characters accepted by Python.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 306–324why, one step back306307Filters and tests are looked up in separate namespaces and have slightly308modified identifier syntax. Filters and tests may contain dots to group309filters and tests by topic. For example it's perfectly valid to add a310function into the filter dict and call it `to.unicode`. The regular311expression for filter and test identifiers is312``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.313314315Undefined Types316---------------317318These classes can be used as undefined types. The :class:`Environment`319constructor takes an `undefined` parameter that can be one of those classes320or a custom subclass of :class:`Undefined`. Whenever the template engine is321unable to look up a name or access an attribute one of those objects is322created and returned. Some operations on undefined values are then allowed,323others fail.324Add ChainableUndefined allowing getattr & getitem (#997)Étienne Pelletierbefore adoption19133d4
line 325why, one step back325The closest to regular Python behavior is the :class:`StrictUndefined` whichMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 326–327why, one step back326disallows all operations beside testing if it's an undefined object.327Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 328why, one step back328.. autoclass:: jinja2.Undefined()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 329–354why, one step back329330 .. attribute:: _undefined_hint331332 Either `None` or an unicode string with the error message for333 the undefined object.334335 .. attribute:: _undefined_obj336337 Either `None` or the owner object that caused the undefined object338 to be created (for example because an attribute does not exist).339340 .. attribute:: _undefined_name341342 The name for the undefined variable / attribute or just `None`343 if no such information exists.344345 .. attribute:: _undefined_exception346347 The exception that the undefined object wants to raise. This348 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.349350 .. method:: _fail_with_undefined_error(\*args, \**kwargs)351352 When called with any arguments this method raises353 :attr:`_undefined_exception` with an error message generated354 from the undefined hints stored on the undefined object.Add ChainableUndefined allowing getattr & getitem (#997)Étienne Pelletierbefore adoption19133d4
line 355why, one step back355Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 356why, one step back356.. autoclass:: jinja2.ChainableUndefined()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 357why, one step back357Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 358why, one step back358.. autoclass:: jinja2.DebugUndefined()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 359why, one step back359Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 360why, one step back360.. autoclass:: jinja2.StrictUndefined()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 361–364why, one step back361362There is also a factory function that can decorate undefined objects to363implement logging on failures:364Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 365why, one step back365.. autofunction:: jinja2.make_logging_undefinedMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 366–384why, one step back366367Undefined objects are created by calling :attr:`undefined`.368369.. admonition:: Implementation370371 :class:`Undefined` objects are implemented by overriding the special372 `__underscore__` methods. For example the default :class:`Undefined`373 class implements `__unicode__` in a way that it returns an empty374 string, however `__int__` and others still fail with an exception. To375 allow conversion to int by returning ``0`` you can implement your own::376377 class NullUndefined(Undefined):378 def __int__(self):379 return 0380 def __float__(self):381 return 0.0382383 To disallow a method, just override it and raise384 :attr:`~Undefined._undefined_exception`. Because this is a very commonMerge pull request #943 from RubenGarcia/masterDavid Lordbefore adoption6e08416
line 385why, one step back385 idiom in undefined objects there is the helper methodMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 386–396why, one step back386 :meth:`~Undefined._fail_with_undefined_error` that does the error raising387 automatically. Here a class that works like the regular :class:`Undefined`388 but chokes on iteration::389390 class NonIterableUndefined(Undefined):391 __iter__ = Undefined._fail_with_undefined_error392393394The Context395-----------396Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 397why, one step back397.. autoclass:: jinja2.runtime.Context()Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 398–440why, one step back398 :members: resolve, get_exported, get_all399400 .. attribute:: parent401402 A dict of read only, global variables the template looks up. These403 can either come from another :class:`Context`, from the404 :attr:`Environment.globals` or :attr:`Template.globals` or points405 to a dict created by combining the globals with the variables406 passed to the render function. It must not be altered.407408 .. attribute:: vars409410 The template local variables. This list contains environment and411 context functions from the :attr:`parent` scope as well as local412 modifications and exported variables from the template. The template413 will modify this dict during template evaluation but filters and414 context functions are not allowed to modify it.415416 .. attribute:: environment417418 The environment that loaded the template.419420 .. attribute:: exported_vars421422 This set contains all the names the template exports. The values for423 the names are in the :attr:`vars` dict. In order to get a copy of the424 exported variables as dict, :meth:`get_exported` can be used.425426 .. attribute:: name427428 The load name of the template owning this context.429430 .. attribute:: blocks431432 A dict with the current mapping of blocks in the template. The keys433 in this dict are the names of the blocks, and the values a list of434 blocks registered. The last item in each list is the current active435 block (latest in the inheritance chain).436437 .. attribute:: eval_ctx438439 The current :ref:`eval-context`.440Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 441why, one step back441 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 442–446why, one step back442443444.. admonition:: Implementation445446 Context is immutable for the same reason Python's frame locals areMerge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 447why, one step back447 immutable inside functions. Both Jinja and Python are not using theMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 448–450why, one step back448 context / frame locals as data storage for variables but only as primary449 data source.450Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 451why, one step back451 When a template accesses a variable the template does not define, JinjaMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 452–467why, one step back452 looks up the variable in the context, after that the variable is treated453 as if it was defined in the template.454455456.. _loaders:457458Loaders459-------460461Loaders are responsible for loading templates from a resource such as the462file system. The environment will keep the compiled modules in memory like463Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in464size by default and templates are automatically reloaded.465All loaders are subclasses of :class:`BaseLoader`. If you want to create your466own loader, subclass :class:`BaseLoader` and override `get_source`.467Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 468why, one step back468.. autoclass:: jinja2.BaseLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 469–470why, one step back469 :members: get_source, load470Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 471why, one step back471Here a list of the builtin loaders Jinja provides:Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 472why, one step back472Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 473why, one step back473.. autoclass:: jinja2.FileSystemLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 474why, one step back474Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 475why, one step back475.. autoclass:: jinja2.PackageLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 476why, one step back476Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 477why, one step back477.. autoclass:: jinja2.DictLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 478why, one step back478Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 479why, one step back479.. autoclass:: jinja2.FunctionLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 480why, one step back480Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 481why, one step back481.. autoclass:: jinja2.PrefixLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 482why, one step back482Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 483why, one step back483.. autoclass:: jinja2.ChoiceLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 484why, one step back484Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 485why, one step back485.. autoclass:: jinja2.ModuleLoaderMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 486–502why, one step back486487488.. _bytecode-cache:489490Bytecode Cache491--------------492493Jinja 2.1 and higher support external bytecode caching. Bytecode caches make494it possible to store the generated bytecode on the file system or a different495location to avoid parsing the templates on first use.496497This is especially useful if you have a web application that is initialized on498the first request and Jinja compiles many templates at once which slows down499the application.500501To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.502Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 503why, one step back503.. autoclass:: jinja2.BytecodeCacheMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 504–505why, one step back504 :members: load_bytecode, dump_bytecode, clear505Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 506why, one step back506.. autoclass:: jinja2.bccache.BucketMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 507–524why, one step back507 :members: write_bytecode, load_bytecode, bytecode_from_string,508 bytecode_to_string, reset509510 .. attribute:: environment511512 The :class:`Environment` that created the bucket.513514 .. attribute:: key515516 The unique cache key for this bucket517518 .. attribute:: code519520 The bytecode if it's loaded, otherwise `None`.521522523Builtin bytecode caches:524Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 525why, one step back525.. autoclass:: jinja2.FileSystemBytecodeCacheMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 526why, one step back526Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 527why, one step back527.. autoclass:: jinja2.MemcachedBytecodeCacheMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 528–532why, one step back528529530Async Support531-------------532Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2
line 533why, one step back533.. versionadded:: 2.9Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 534why, one step back534Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2
lines 535–539why, one step back535Jinja supports the Python ``async`` and ``await`` syntax. For the536template designer, this support (when enabled) is entirely transparent,537templates continue to look exactly the same. However, developers should538be aware of the implementation as it affects what types of APIs you can539use.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 540why, one step back540Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2
lines 541–544why, one step back541By default, async support is disabled. Enabling it will cause the542environment to compile different code behind the scenes in order to543handle async and sync code in an asyncio event loop. This has the544following implications:Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 545why, one step back545Merge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2
lines 546–557why, one step back546- Template rendering requires an event loop to be available to the547 current thread. :func:`asyncio.get_event_loop` must return an event548 loop.549- The compiled code uses ``await`` for functions and attributes, and550 uses ``async for`` loops. In order to support using both async and551 sync functions in this context, a small wrapper is placed around552 all calls and access, which add overhead compared to purely async553 code.554- Sync methods and filters become wrappers around their corresponding555 async implementations where needed. For example, ``render`` invokes556 ``async_render``, and ``|map`` supports async iterables.557Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 558why, one step back558Awaitable objects can be returned from functions in templates and anyMerge pull request #1149 from davidbrochart/fix_docDavid Lordbefore adoption2a70ef2
lines 559–563why, one step back559function call in a template will automatically await the result. The560``await`` you would normally add in Python is implied. For example, you561can provide a method that asynchronously loads data from a database, and562from the template designer's point of view it can be called like any563other function.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 564–573why, one step back564565566.. _policies:567568Policies569--------570571Starting with Jinja 2.9 policies can be configured on the environment572which can slightly influence how filters and other template constructs573behave. They can be configured with theMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 574why, one step back574:attr:`~jinja2.Environment.policies` attribute.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 575–580why, one step back575576Example::577578 env.policies['urlize.rel'] = 'nofollow noopener'579580``compiler.ascii_str``:Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 581why, one step back581 This boolean controls on Python 2 if Jinja should store ASCII onlyMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 582–589why, one step back582 literals as bytestring instead of unicode strings. This used to be583 always enabled for Jinja versions below 2.9 and now can be changed.584 Traditionally it was done this way since some APIs in Python 2 failed585 badly for unicode strings (for instance the datetime strftime API).586 Now however sometimes the inverse is true (for instance str.format).587 If this is set to False then all strings are stored as unicode588 internally.589Merge branch '2.9-maintenance'Armin Ronacherbefore adoption5a8e771
lines 590–595why, one step back590``truncate.leeway``:591 Configures the leeway default for the `truncate` filter. Leeway as592 introduced in 2.9 but to restore compatibility with older templates593 it can be configured to `0` to get the old behavior back. The default594 is `5`.595Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 596–616why, one step back596``urlize.rel``:597 A string that defines the items for the `rel` attribute of generated598 links with the `urlize` filter. These items are always added. The599 default is `noopener`.600601``urlize.target``:602 The default target that is issued for links from the `urlize` filter603 if no other target is defined by the call explicitly.604605``json.dumps_function``:606 If this is set to a value other than `None` then the `tojson` filter607 will dump with this function instead of the default one. Note that608 this function should accept arbitrary extra arguments which might be609 passed in the future from the filter. Currently the only argument610 that might be passed is `indent`. The default dump function is611 ``json.dumps``.612613``json.dumps_kwargs``:614 Keyword arguments to be passed to the dump function. The default is615 ``{'sort_keys': True}``.616Add support for `{% trans trimmed ... %}`Adrian Moennichbefore adoptione605ff1
lines 617–623why, one step back617.. _ext-i18n-trimmed:618619``ext.i18n.trimmed``:620 If this is set to `True`, ``{% trans %}`` blocks of the621 :ref:`i18n-extension` will always unify linebreaks and surrounding622 whitespace as if the `trimmed` modifier was used.623Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 624–628why, one step back624625Utilities626---------627628These helper functions and classes are useful if you add custom filters orMerge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 629why, one step back629functions to a Jinja environment.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 630why, one step back630Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 631why, one step back631.. autofunction:: jinja2.environmentfilterMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 632why, one step back632Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 633why, one step back633.. autofunction:: jinja2.contextfilterMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 634why, one step back634Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 635why, one step back635.. autofunction:: jinja2.evalcontextfilterMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 636why, one step back636Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 637why, one step back637.. autofunction:: jinja2.environmentfunctionMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 638why, one step back638Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 639why, one step back639.. autofunction:: jinja2.contextfunctionMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 640why, one step back640Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 641why, one step back641.. autofunction:: jinja2.evalcontextfunctionMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 642–651why, one step back642643.. function:: escape(s)644645 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`646 to HTML-safe sequences. Use this if you need to display text that might647 contain such characters in HTML. This function will not escaped objects648 that do have an HTML representation such as already escaped data.649650 The return value is a :class:`Markup` string.651Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 652why, one step back652.. autofunction:: jinja2.clear_cachesMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 653why, one step back653Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 654why, one step back654.. autofunction:: jinja2.is_undefinedMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 655why, one step back655Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 656why, one step back656.. autoclass:: jinja2.Markup([string])Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 657–660why, one step back657 :members: escape, unescape, striptags658659.. admonition:: Note660Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
line 661why, one step back661 The Jinja :class:`Markup` class is compatible with at least Pylons andMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 662–668why, one step back662 Genshi. It's expected that more template engines and framework will pick663 up the `__html__` concept soon.664665666Exceptions667----------668Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 669why, one step back669.. autoexception:: jinja2.TemplateErrorMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 670why, one step back670Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 671why, one step back671.. autoexception:: jinja2.UndefinedErrorMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 672why, one step back672Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 673why, one step back673.. autoexception:: jinja2.TemplateNotFoundMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 674why, one step back674Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 675why, one step back675.. autoexception:: jinja2.TemplatesNotFoundMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 676why, one step back676Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 677why, one step back677.. autoexception:: jinja2.TemplateSyntaxErrorMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 678–699why, one step back678679 .. attribute:: message680681 The error message as utf-8 bytestring.682683 .. attribute:: lineno684685 The line number where the error occurred686687 .. attribute:: name688689 The load name for the template as unicode string.690691 .. attribute:: filename692693 The filename that loaded the template as bytestring in the encoding694 of the file system (most likely utf-8 or mbcs on Windows systems).695696 The reason why the filename and error message are bytestrings and not697 unicode strings is that Python 2.x is not using unicode for exceptions698 and tracebacks as well as the compiler. This will change with Python 3.699Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 700why, one step back700.. autoexception:: jinja2.TemplateRuntimeErrorMerge pull request #684 from ThiefMaster/set-namespacesAdrianbefore adoptionc7dfa21
line 701why, one step back701Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 702why, one step back702.. autoexception:: jinja2.TemplateAssertionErrorMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 703–743why, one step back703704705.. _writing-filters:706707Custom Filters708--------------709710Custom filters are just regular Python functions that take the left side of711the filter as first argument and the arguments passed to the filter as712extra arguments or keyword arguments.713714For example in the filter ``{{ 42|myfilter(23) }}`` the function would be715called with ``myfilter(42, 23)``. Here for example a simple filter that can716be applied to datetime objects to format them::717718 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):719 return value.strftime(format)720721You can register it on the template environment by updating the722:attr:`~Environment.filters` dict on the environment::723724 environment.filters['datetimeformat'] = datetimeformat725726Inside the template it can then be used as follows:727728.. sourcecode:: jinja729730 written on: {{ article.pub_date|datetimeformat }}731 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}732733Filters can also be passed the current template context or environment. This734is useful if a filter wants to return an undefined value or check the current735:attr:`~Environment.autoescape` setting. For this purpose three decorators736exist: :func:`environmentfilter`, :func:`contextfilter` and737:func:`evalcontextfilter`.738739Here a small example filter that breaks a text into HTML line breaks and740paragraphs and marks the return value as safe HTML string if autoescaping is741enabled::742743 import reMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 744why, one step back744 from jinja2 import evalcontextfilter, Markup, escapeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 745why, one step back745Merge pull request #929 from ExplodingCabbage/fix-nl2brDavid Lordbefore adoptiondd6c765
line 746why, one step back746 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 747–756why, one step back747748 @evalcontextfilter749 def nl2br(eval_ctx, value):750 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))751 for p in _paragraph_re.split(escape(value)))752 if eval_ctx.autoescape:753 result = Markup(result)754 return result755756Context filters work the same just that the first argument is the currentMerge branch '2.9-maintenance'Armin Ronacherbefore adoptionc1cd154
line 757why, one step back757active :class:`Context` rather than the environment.Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 758–809why, one step back758759760.. _eval-context:761762Evaluation Context763------------------764765The evaluation context (short eval context or eval ctx) is a new object766introduced in Jinja 2.4 that makes it possible to activate and deactivate767compiled features at runtime.768769Currently it is only used to enable and disable the automatic escaping but770can be used for extensions as well.771772In previous Jinja versions filters and functions were marked as773environment callables in order to check for the autoescape status from the774environment. In new versions it's encouraged to check the setting from the775evaluation context instead.776777Previous versions::778779 @environmentfilter780 def filter(env, value):781 result = do_something(value)782 if env.autoescape:783 result = Markup(result)784 return result785786In new versions you can either use a :func:`contextfilter` and access the787evaluation context from the actual context, or use a788:func:`evalcontextfilter` which directly passes the evaluation context to789the function::790791 @contextfilter792 def filter(context, value):793 result = do_something(value)794 if context.eval_ctx.autoescape:795 result = Markup(result)796 return result797798 @evalcontextfilter799 def filter(eval_ctx, value):800 result = do_something(value)801 if eval_ctx.autoescape:802 result = Markup(result)803 return result804805The evaluation context must not be modified at runtime. Modifications806must only happen with a :class:`nodes.EvalContextModifier` and807:class:`nodes.ScopedEvalContextModifier` from an extension, not on the808eval context object itself.809Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 810why, one step back810.. autoclass:: jinja2.nodes.EvalContextMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 811–839why, one step back811812 .. attribute:: autoescape813814 `True` or `False` depending on if autoescaping is active or not.815816 .. attribute:: volatile817818 `True` if the compiler cannot evaluate some expressions at compile819 time. At runtime this should always be `False`.820821822.. _writing-tests:823824Custom Tests825------------826827Tests work like filters just that there is no way for a test to get access828to the environment or context and that they can't be chained. The return829value of a test should be `True` or `False`. The purpose of a test is to830give the template designers the possibility to perform type and conformability831checks.832833Here a simple test that checks if a variable is a prime number::834835 import math836837 def is_prime(n):838 if n == 2:839 return TrueMerge branch '2.10.x'David Lordbefore adoption13cc9f4
line 840why, one step back840 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 841–843why, one step back841 if n % i == 0:842 return False843 return TrueMerge pull request #891 from jdufresne/wsDavid Lordbefore adoptionf9bb207
line 844why, one step back844Merge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 845–917why, one step back845846You can register it on the template environment by updating the847:attr:`~Environment.tests` dict on the environment::848849 environment.tests['prime'] = is_prime850851A template designer can then use the test like this:852853.. sourcecode:: jinja854855 {% if 42 is prime %}856 42 is a prime number857 {% else %}858 42 is not a prime number859 {% endif %}860861862.. _global-namespace:863864The Global Namespace865--------------------866867Variables stored in the :attr:`Environment.globals` dict are special as they868are available for imported templates too, even if they are imported without869context. This is the place where you can put variables and functions870that should be available all the time. Additionally :attr:`Template.globals`871exist that are variables available to a specific template that are available872to all :meth:`~Template.render` calls.873874875.. _low-level-api:876877Low Level API878-------------879880The low level API exposes functionality that can be useful to understand some881implementation details, debugging purposes or advanced :ref:`extension882<jinja-extensions>` techniques. Unless you know exactly what you are doing we883don't recommend using any of those.884885.. automethod:: Environment.lex886887.. automethod:: Environment.parse888889.. automethod:: Environment.preprocess890891.. automethod:: Template.new_context892893.. method:: Template.root_render_func(context)894895 This is the low level render function. It's passed a :class:`Context`896 that has to be created by :meth:`new_context` of the same template or897 a compatible template. This render function is generated by the898 compiler from the template code and returns a generator that yields899 unicode strings.900901 If an exception in the template code happens the template engine will902 not rewrite the exception but pass through the original one. As a903 matter of fact this function should only be called from within a904 :meth:`render` / :meth:`generate` / :meth:`stream` call.905906.. attribute:: Template.blocks907908 A dict of block render functions. Each of these functions works exactly909 like the :meth:`root_render_func` with the same limitations.910911.. attribute:: Template.is_up_to_date912913 This attribute is `False` if there is a newer version of the template914 available, otherwise `True`.915916.. admonition:: Note917Merge pull request #1087 from pallets/jinja-nameDavid Lordbefore adoption1af1205
lines 918–920why, one step back918 The low-level API is fragile. Future Jinja versions will try not to919 change it in a backwards incompatible way but modifications in the Jinja920 core may shine through. For example if Jinja introduces a new AST nodeMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
lines 921–932why, one step back921 in later versions that may be returned by :meth:`~Environment.parse`.922923The Meta API924------------925926.. versionadded:: 2.2927928The meta API returns some information about abstract syntax trees that929could help applications to implement more advanced template concepts. All930the functions of the meta API operate on an abstract syntax tree as931returned by the :meth:`Environment.parse` method.932Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 933why, one step back933.. autofunction:: jinja2.meta.find_undeclared_variablesMerge branch '2.9-maintenance'Armin Ronacherbefore adoption793ddd4
line 934why, one step back934Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 935why, one step back935.. autofunction:: jinja2.meta.find_referenced_templates