api.rst
This file
Path
docs/api.rst
922 lines · 30.2 KiB
Last changed by
Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
History of this fileTake it
The walk stopped after 200 commits: lines older than 9176fbd point at it.
Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
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 #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 5–7why, one step back5 :noindex:6 :synopsis: public Jinja API7Merge branch '2.11.x'David Lordbefore adoptionc074fd5
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 pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 12–27why, one step back1213Basics14------1516Jinja uses a central object called the template :class:`Environment`.17Instances 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 application24initialization and use that to load templates. In some cases however, it's25useful to have multiple environments side by side, if different configurations26are in use.27Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 28–29why, one step back28The simplest way to configure Jinja to load templates for your29application is to use :class:`~loaders.PackageLoader`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 30why, one step back30Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 31–32why, one step back31.. code-block:: python32Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 33why, one step back33 from jinja2 import Environment, PackageLoader, select_autoescapeMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 34why, one step back34 env = Environment(Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 35–36why, one step back35 loader=PackageLoader("yourapp"),36 autoescape=select_autoescape()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 37–38why, one step back37 )38Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 39–43why, one step back39This will create a template environment with a loader that looks up40templates in the ``templates`` folder inside the ``yourapp`` Python41package (or next to the ``yourapp.py`` Python module). It also enables42autoescaping for HTML files. This loader only requires that ``yourapp``43is importable, it figures out the absolute path to the folder for you.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 44why, one step back44Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 45–48why, one step back45Different loaders are available to load templates in other ways or from46other locations. They're listed in the `Loaders`_ section below. You can47also write your own if you want to load templates from a source that's48more specialized to your project.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 49why, one step back49Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 50–51why, one step back50To load a template from this environment, call the :meth:`get_template`51method, which returns the loaded :class:`Template`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 52why, one step back52Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
line 53why, one step back53.. code-block:: pythonMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 54why, one step back54Merge pull request #1224 from pallets/loader-docsDavid Lordbefore adoptionca8b0b0
lines 55–61why, one step back55 template = env.get_template("mytemplate.html")5657To render it with some variables, call the :meth:`render` method.5859.. code-block:: python6061 print(template.render(the="variables", go="here"))Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 62–98why, one step back6263Using a template loader rather than passing strings to :class:`Template`64or :meth:`Environment.from_string` has multiple advantages. Besides being65a lot easier to use it also enables template inheritance.6667.. admonition:: Notes on Autoescaping6869 In future versions of Jinja we might enable autoescaping by default70 for security reasons. As such you are encouraged to explicitly71 configure autoescaping now instead of relying on the default.727374High Level API75--------------7677The high-level API is the API you will use in the application to load and78render Jinja templates. The :ref:`low-level-api` on the other side is only79useful if you want to dig deeper into Jinja or :ref:`develop extensions80<jinja-extensions>`.8182.. autoclass:: Environment([options])83 :members: from_string, get_template, select_template,84 get_or_select_template, join_path, extend, compile_expression,85 compile_templates, list_templates, add_extension8687 .. attribute:: shared8889 If a template was created by using the :class:`Template` constructor90 an environment is created automatically. These environments are91 created as shared environments which means that multiple templates92 may have the same anonymous environment. For all shared environments93 this attribute is `True`, else `False`.9495 .. attribute:: sandboxed9697 If the environment is sandboxed this attribute is `True`. For the98 sandbox mode have a look at the documentation for theMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 99why, one step back99 :class:`~jinja2.sandbox.SandboxedEnvironment`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 100–116why, one step back100101 .. attribute:: filters102103 A dict of filters for this environment. As long as no template was104 loaded it's safe to add new filters or remove old. For custom filters105 see :ref:`writing-filters`. For valid filter names have a look at106 :ref:`identifier-naming`.107108 .. attribute:: tests109110 A dict of test functions for this environment. As long as no111 template was loaded it's safe to modify this dict. For custom tests112 see :ref:`writing-tests`. For valid test names have a look at113 :ref:`identifier-naming`.114115 .. attribute:: globals116Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 117–120why, one step back117 A dict of variables that are available in every template loaded118 by the environment. As long as no template was loaded it's safe119 to modify this. For more details see :ref:`global-namespace`.120 For valid object names see :ref:`identifier-naming`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 121–138why, one step back121122 .. attribute:: policies123124 A dictionary with :ref:`policies`. These can be reconfigured to125 change the runtime behavior or certain template features. Usually126 these are security related.127128 .. attribute:: code_generator_class129130 The class used for code generation. This should not be changed131 in most cases, unless you need to modify the Python code a132 template compiles to.133134 .. attribute:: context_class135136 The context used for templates. This should not be changed137 in most cases, unless you need to modify internals of how138 template variables are handled. For details, seeMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 139why, one step back139 :class:`~jinja2.runtime.Context`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 140–182why, one step back140141 .. automethod:: overlay([options])142143 .. method:: undefined([hint, obj, name, exc])144145 Creates a new :class:`Undefined` object for `name`. This is useful146 for filters or functions that may return undefined objects for147 some operations. All parameters except of `hint` should be provided148 as keyword parameters for better readability. The `hint` is used as149 error message for the exception if provided, otherwise the error150 message will be generated from `obj` and `name` automatically. The exception151 provided as `exc` is raised if something with the generated undefined152 object is done that the undefined object does not allow. The default153 exception is :exc:`UndefinedError`. If a `hint` is provided the154 `name` may be omitted.155156 The most common way to create an undefined object is by providing157 a name only::158159 return environment.undefined(name='some_name')160161 This means that the name `some_name` is not defined. If the name162 was from an attribute of an object it makes sense to tell the163 undefined object the holder object to improve the error message::164165 if not hasattr(obj, 'attr'):166 return environment.undefined(obj=obj, name='attr')167168 For a more complex example you can provide a hint. For example169 the :func:`first` filter creates an undefined object that way::170171 return environment.undefined('no first item, sequence was empty')172173 If it the `name` or `obj` is known (for example because an attribute174 was accessed) it should be passed to the undefined object, even if175 a custom `hint` is provided. This gives undefined objects the176 possibility to enhance the error message.177178.. autoclass:: Template179 :members: module, make_module180181 .. attribute:: globals182Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 183–187why, one step back183 A dict of variables that are available every time the template184 is rendered, without needing to pass them during render. This185 should not be modified, as depending on how the template was186 loaded it may be shared with the environment and other187 templates.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 188why, one step back188Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 189–197why, one step back189 Defaults to :attr:`Environment.globals` unless extra values are190 passed to :meth:`Environment.get_template`.191192 Globals are only intended for data that is common to every193 render of the template. Specific data should be passed to194 :meth:`render`.195196 See :ref:`global-namespace`.197Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 198–218why, one step back198 .. attribute:: name199200 The loading name of the template. If the template was loaded from a201 string this is `None`.202203 .. attribute:: filename204205 The filename of the template on the file system if it was loaded from206 there. Otherwise this is `None`.207208 .. automethod:: render([context])209210 .. automethod:: generate([context])211212 .. automethod:: stream([context])213214 .. automethod:: render_async([context])215216 .. automethod:: generate_async([context])217218Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 219why, one step back219.. autoclass:: jinja2.environment.TemplateStream()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 220–234why, one step back220 :members: disable_buffering, enable_buffering, dump221222223Autoescaping224------------225226.. versionchanged:: 2.4227228Jinja now comes with autoescaping support. As of Jinja 2.9 the229autoescape extension is removed and built-in. However autoescaping is230not yet enabled by default though this will most likely change in the231future. It's recommended to configure a sensible default for232autoescaping. This makes it possible to enable and disable autoescaping233on a per-template basis (HTML versus text for instance).234Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 235why, one step back235.. autofunction:: jinja2.select_autoescapeMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 236–238why, one step back236237Here a recommended setup that enables autoescaping for templates ending238in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by defaultMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 239why, one step back239for all other extensions. You can use the :func:`~jinja2.select_autoescape`Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 240–241why, one step back240function for this::241Merge branch '2.11.x'David Lordbefore adoption076d380
line 242why, one step back242 from jinja2 import Environment, PackageLoader, select_autoescapeMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 243–268why, one step back243 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),244 loader=PackageLoader('mypackage'))245246The :func:`~jinja.select_autoescape` function returns a function that247works roughly like this::248249 def autoescape(template_name):250 if template_name is None:251 return False252 if template_name.endswith(('.html', '.htm', '.xml'))253254When implementing a guessing autoescape function, make sure you also255accept `None` as valid template name. This will be passed when generating256templates from strings. You should always configure autoescaping as257defaults in the future might change.258259Inside the templates the behaviour can be temporarily changed by using260the `autoescape` block (see :ref:`autoescape-overrides`).261262263.. _identifier-naming:264265Notes on Identifiers266--------------------267268Jinja uses Python naming rules. Valid identifiers can be any combinationMerge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 269why, one step back269of characters accepted by Python.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 270–273why, one step back270271Filters and tests are looked up in separate namespaces and have slightly272modified identifier syntax. Filters and tests may contain dots to group273filters and tests by topic. For example it's perfectly valid to add aMerge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 274why, one step back274function into the filter dict and call it `to.str`. The regularMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 275why, one step back275expression for filter and test identifiers isMerge branch '3.0.x'David Lordbefore adoption896a621
line 276why, one step back276``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*``.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 277–291why, one step back277278279Undefined Types280---------------281282These classes can be used as undefined types. The :class:`Environment`283constructor takes an `undefined` parameter that can be one of those classes284or a custom subclass of :class:`Undefined`. Whenever the template engine is285unable to look up a name or access an attribute one of those objects is286created and returned. Some operations on undefined values are then allowed,287others fail.288289The closest to regular Python behavior is the :class:`StrictUndefined` which290disallows all operations beside testing if it's an undefined object.291Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 292why, one step back292.. autoclass:: jinja2.Undefined()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 293–295why, one step back293294 .. attribute:: _undefined_hint295Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 296–297why, one step back296 Either `None` or a string with the error message for the297 undefined object.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 298–319why, one step back298299 .. attribute:: _undefined_obj300301 Either `None` or the owner object that caused the undefined object302 to be created (for example because an attribute does not exist).303304 .. attribute:: _undefined_name305306 The name for the undefined variable / attribute or just `None`307 if no such information exists.308309 .. attribute:: _undefined_exception310311 The exception that the undefined object wants to raise. This312 is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.313314 .. method:: _fail_with_undefined_error(\*args, \**kwargs)315316 When called with any arguments this method raises317 :attr:`_undefined_exception` with an error message generated318 from the undefined hints stored on the undefined object.319Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 320why, one step back320.. autoclass:: jinja2.ChainableUndefined()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 321why, one step back321Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 322why, one step back322.. autoclass:: jinja2.DebugUndefined()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 323why, one step back323Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 324why, one step back324.. autoclass:: jinja2.StrictUndefined()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 325–328why, one step back325326There is also a factory function that can decorate undefined objects to327implement logging on failures:328Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 329why, one step back329.. autofunction:: jinja2.make_logging_undefinedMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 330–334why, one step back330331Undefined objects are created by calling :attr:`undefined`.332333.. admonition:: Implementation334Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 335–340why, one step back335 :class:`Undefined` is implemented by overriding the special336 ``__underscore__`` methods. For example the default337 :class:`Undefined` class implements ``__str__`` to returns an empty338 string, while ``__int__`` and others fail with an exception. To339 allow conversion to int by returning ``0`` you can implement your340 own subclass.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 341why, one step back341Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 342–343why, one step back342 .. code-block:: python343Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 344–346why, one step back344 class NullUndefined(Undefined):345 def __int__(self):346 return 0Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 347why, one step back347Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 348–350why, one step back348 def __float__(self):349 return 0.0350Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 351–356why, one step back351 To disallow a method, override it and raise352 :attr:`~Undefined._undefined_exception`. Because this is very353 common there is the helper method354 :meth:`~Undefined._fail_with_undefined_error` that raises the error355 with the correct information. Here's a class that works like the356 regular :class:`Undefined` but fails on iteration::Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 357–358why, one step back357358 class NonIterableUndefined(Undefined):Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 359–360why, one step back359 def __iter__(self):360 self._fail_with_undefined_error()Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 361–365why, one step back361362363The Context364-----------365Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 366why, one step back366.. autoclass:: jinja2.runtime.Context()Merge pull request #1393 from pallets/deprecate-legacy-resolveDavid Lordbefore adoption06230b0
line 367why, one step back367 :members: get, resolve, resolve_or_missing, get_exported, get_allMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 368–409why, one step back368369 .. attribute:: parent370371 A dict of read only, global variables the template looks up. These372 can either come from another :class:`Context`, from the373 :attr:`Environment.globals` or :attr:`Template.globals` or points374 to a dict created by combining the globals with the variables375 passed to the render function. It must not be altered.376377 .. attribute:: vars378379 The template local variables. This list contains environment and380 context functions from the :attr:`parent` scope as well as local381 modifications and exported variables from the template. The template382 will modify this dict during template evaluation but filters and383 context functions are not allowed to modify it.384385 .. attribute:: environment386387 The environment that loaded the template.388389 .. attribute:: exported_vars390391 This set contains all the names the template exports. The values for392 the names are in the :attr:`vars` dict. In order to get a copy of the393 exported variables as dict, :meth:`get_exported` can be used.394395 .. attribute:: name396397 The load name of the template owning this context.398399 .. attribute:: blocks400401 A dict with the current mapping of blocks in the template. The keys402 in this dict are the names of the blocks, and the values a list of403 blocks registered. The last item in each list is the current active404 block (latest in the inheritance chain).405406 .. attribute:: eval_ctx407408 The current :ref:`eval-context`.409Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 410why, one step back410 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 411–412why, one step back411412Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 413–418why, one step back413The context is immutable, it prevents modifications, and if it is414modified somehow despite that those changes may not show up. For415performance, Jinja does not use the context as data storage for, only as416a primary data source. Variables that the template does not define are417looked up in the context, but variables the template does define are418stored locally.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 419why, one step back419Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 420–421why, one step back420Instead of modifying the context directly, a function should return421a value that can be assigned to a variable within the template itself.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 422why, one step back422Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 423–425why, one step back423.. code-block:: jinja424425 {% set comments = get_latest_comments() %}Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 426–439why, one step back426427428.. _loaders:429430Loaders431-------432433Loaders are responsible for loading templates from a resource such as the434file system. The environment will keep the compiled modules in memory like435Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in436size by default and templates are automatically reloaded.437All loaders are subclasses of :class:`BaseLoader`. If you want to create your438own loader, subclass :class:`BaseLoader` and override `get_source`.439Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 440why, one step back440.. autoclass:: jinja2.BaseLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 441–444why, one step back441 :members: get_source, load442443Here a list of the builtin loaders Jinja provides:444Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 445why, one step back445.. autoclass:: jinja2.FileSystemLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 446why, one step back446Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 447why, one step back447.. autoclass:: jinja2.PackageLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 448why, one step back448Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 449why, one step back449.. autoclass:: jinja2.DictLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 450why, one step back450Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 451why, one step back451.. autoclass:: jinja2.FunctionLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 452why, one step back452Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 453why, one step back453.. autoclass:: jinja2.PrefixLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 454why, one step back454Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 455why, one step back455.. autoclass:: jinja2.ChoiceLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 456why, one step back456Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 457why, one step back457.. autoclass:: jinja2.ModuleLoaderMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 458–474why, one step back458459460.. _bytecode-cache:461462Bytecode Cache463--------------464465Jinja 2.1 and higher support external bytecode caching. Bytecode caches make466it possible to store the generated bytecode on the file system or a different467location to avoid parsing the templates on first use.468469This is especially useful if you have a web application that is initialized on470the first request and Jinja compiles many templates at once which slows down471the application.472473To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.474Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 475why, one step back475.. autoclass:: jinja2.BytecodeCacheMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 476–477why, one step back476 :members: load_bytecode, dump_bytecode, clear477Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 478why, one step back478.. autoclass:: jinja2.bccache.BucketMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 479–496why, one step back479 :members: write_bytecode, load_bytecode, bytecode_from_string,480 bytecode_to_string, reset481482 .. attribute:: environment483484 The :class:`Environment` that created the bucket.485486 .. attribute:: key487488 The unique cache key for this bucket489490 .. attribute:: code491492 The bytecode if it's loaded, otherwise `None`.493494495Builtin bytecode caches:496Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 497why, one step back497.. autoclass:: jinja2.FileSystemBytecodeCacheMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 498why, one step back498Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 499why, one step back499.. autoclass:: jinja2.MemcachedBytecodeCacheMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 500–504why, one step back500501502Async Support503-------------504Merge branch '2.11.x'David Lordbefore adoption45a76a3
line 505why, one step back505.. versionadded:: 2.9Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 506why, one step back506Merge branch '2.11.x'David Lordbefore adoption45a76a3
lines 507–511why, one step back507Jinja supports the Python ``async`` and ``await`` syntax. For the508template designer, this support (when enabled) is entirely transparent,509templates continue to look exactly the same. However, developers should510be aware of the implementation as it affects what types of APIs you can511use.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 512why, one step back512Merge branch '2.11.x'David Lordbefore adoption45a76a3
lines 513–516why, one step back513By default, async support is disabled. Enabling it will cause the514environment to compile different code behind the scenes in order to515handle async and sync code in an asyncio event loop. This has the516following implications:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 517why, one step back517Merge branch '2.11.x'David Lordbefore adoption45a76a3
line 518why, one step back518- Template rendering requires an event loop to be available to theMerge branch '3.0.x'David Lordbefore adoptioncdbda09
lines 519–520why, one step back519 current thread. :func:`asyncio.get_running_loop` must return an520 event loop.Merge branch '2.11.x'David Lordbefore adoption45a76a3
lines 521–523why, one step back521- The compiled code uses ``await`` for functions and attributes, and522 uses ``async for`` loops. In order to support using both async and523 sync functions in this context, a small wrapper is placed aroundMerge branch '3.0.x'David Lordbefore adoptioncdbda09
line 524why, one step back524 all calls and access, which adds overhead compared to purely asyncMerge branch '2.11.x'David Lordbefore adoption45a76a3
lines 525–529why, one step back525 code.526- Sync methods and filters become wrappers around their corresponding527 async implementations where needed. For example, ``render`` invokes528 ``async_render``, and ``|map`` supports async iterables.529Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 530why, one step back530Awaitable objects can be returned from functions in templates and anyMerge branch '2.11.x'David Lordbefore adoption45a76a3
lines 531–535why, one step back531function call in a template will automatically await the result. The532``await`` you would normally add in Python is implied. For example, you533can provide a method that asynchronously loads data from a database, and534from the template designer's point of view it can be called like any535other function.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 536–545why, one step back536537538.. _policies:539540Policies541--------542543Starting with Jinja 2.9 policies can be configured on the environment544which can slightly influence how filters and other template constructs545behave. They can be configured with theMerge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 546why, one step back546:attr:`~jinja2.Environment.policies` attribute.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 547–566why, one step back547548Example::549550 env.policies['urlize.rel'] = 'nofollow noopener'551552``truncate.leeway``:553 Configures the leeway default for the `truncate` filter. Leeway as554 introduced in 2.9 but to restore compatibility with older templates555 it can be configured to `0` to get the old behavior back. The default556 is `5`.557558``urlize.rel``:559 A string that defines the items for the `rel` attribute of generated560 links with the `urlize` filter. These items are always added. The561 default is `noopener`.562563``urlize.target``:564 The default target that is issued for links from the `urlize` filter565 if no other target is defined by the call explicitly.566Merge pull request #1195 from bebleo/add_mailto_link_supportDavid Lordbefore adoptionf1b1caf
lines 567–570why, one step back567``urlize.extra_schemes``:568 Recognize URLs that start with these schemes in addition to the569 default ``http://``, ``https://``, and ``mailto:``.570Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 571–596why, one step back571``json.dumps_function``:572 If this is set to a value other than `None` then the `tojson` filter573 will dump with this function instead of the default one. Note that574 this function should accept arbitrary extra arguments which might be575 passed in the future from the filter. Currently the only argument576 that might be passed is `indent`. The default dump function is577 ``json.dumps``.578579``json.dumps_kwargs``:580 Keyword arguments to be passed to the dump function. The default is581 ``{'sort_keys': True}``.582583.. _ext-i18n-trimmed:584585``ext.i18n.trimmed``:586 If this is set to `True`, ``{% trans %}`` blocks of the587 :ref:`i18n-extension` will always unify linebreaks and surrounding588 whitespace as if the `trimmed` modifier was used.589590591Utilities592---------593594These helper functions and classes are useful if you add custom filters or595functions to a Jinja environment.596Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 597why, one step back597.. autofunction:: jinja2.pass_contextMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 598why, one step back598Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 599–602why, one step back599.. autofunction:: jinja2.pass_eval_context600601.. autofunction:: jinja2.pass_environment602Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 603why, one step back603.. autofunction:: jinja2.clear_cachesMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 604why, one step back604Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 605why, one step back605.. autofunction:: jinja2.is_undefinedMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 606–610why, one step back606607608Exceptions609----------610Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 611why, one step back611.. autoexception:: jinja2.TemplateErrorMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 612why, one step back612Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 613why, one step back613.. autoexception:: jinja2.UndefinedErrorMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 614why, one step back614Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 615why, one step back615.. autoexception:: jinja2.TemplateNotFoundMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 616why, one step back616Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 617why, one step back617.. autoexception:: jinja2.TemplatesNotFoundMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 618why, one step back618Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 619why, one step back619.. autoexception:: jinja2.TemplateSyntaxErrorMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 620–622why, one step back620621 .. attribute:: message622Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 623why, one step back623 The error message.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 624–626why, one step back624625 .. attribute:: lineno626Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 627why, one step back627 The line number where the error occurred.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 628–630why, one step back628629 .. attribute:: name630Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 631why, one step back631 The load name for the template.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 632–634why, one step back632633 .. attribute:: filename634Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 635–636why, one step back635 The filename that loaded the template in the encoding of the636 file system (most likely utf-8, or mbcs on Windows systems).Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 637why, one step back637Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 638why, one step back638.. autoexception:: jinja2.TemplateRuntimeErrorMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 639why, one step back639Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 640why, one step back640.. autoexception:: jinja2.TemplateAssertionErrorMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 641–647why, one step back641642643.. _writing-filters:644645Custom Filters646--------------647Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 648–650why, one step back648Filters are Python functions that take the value to the left of the649filter as the first argument and produce a new value. Arguments passed650to the filter are passed after the value.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 651why, one step back651Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 652–653why, one step back652For example, the filter ``{{ 42|myfilter(23) }}`` is called behind the653scenes as ``myfilter(42, 23)``.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 654why, one step back654Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 655–657why, one step back655Jinja comes with some :ref:`built-in filters <builtin-filters>`. To use656a custom filter, write a function that takes at least a ``value``657argument, then register it in :attr:`Environment.filters`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 658why, one step back658Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 659why, one step back659Here's a filter that formats datetime objects:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 660why, one step back660Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 661why, one step back661.. code-block:: pythonMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 662why, one step back662Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 663–664why, one step back663 def datetime_format(value, format="%H:%M %d-%m-%y"):664 return value.strftime(format)Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 665why, one step back665Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 666–669why, one step back666 environment.filters["datetime_format"] = datetime_format667668Now it can be used in templates:669Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 670–671why, one step back670.. sourcecode:: jinja671Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 672–673why, one step back672 {{ article.pub_date|datetimeformat }}673 {{ article.pub_date|datetimeformat("%B %Y") }}Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 674why, one step back674Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 675–677why, one step back675Some decorators are available to tell Jinja to pass extra information to676the filter. The object is passed as the first argument, making the value677being filtered the second argument.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 678why, one step back678Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 679–681why, one step back679- :func:`pass_environment` passes the :class:`Environment`.680- :func:`pass_eval_context` passes the :ref:`eval-context`.681- :func:`pass_context` passes the currentMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 682why, one step back682 :class:`~jinja2.runtime.Context`.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 683why, one step back683Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 684–686why, one step back684Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>``685tags. It uses the eval context to check if autoescape is currently686enabled before escaping the input and marking the output safe.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 687why, one step back687Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 688why, one step back688.. code-block:: pythonMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 689why, one step back689Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 690why, one step back690 import reMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 691why, one step back691 from jinja2 import pass_eval_contextMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 692–693why, one step back692 from markupsafe import Markup, escape693Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 694why, one step back694 @pass_eval_contextMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 695why, one step back695 def nl2br(eval_ctx, value):Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 696–701why, one step back696 br = "<br>\n"697698 if eval_ctx.autoescape:699 value = escape(value)700 br = Markup(br)701Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 702why, one step back702 result = "\n\n".join(Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 703–704why, one step back703 f"<p>{br.join(p.splitlines())}<\p>"704 for p in re.split(r"(?:\r\n|\r(?!\n)|\n){2,}", value)Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 705why, one step back705 )Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 706why, one step back706 return Markup(result) if autoescape else resultMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 707–708why, one step back707708Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 709why, one step back709.. _writing-tests:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 710why, one step back710Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 711–756why, one step back711Custom Tests712------------713714Test are Python functions that take the value to the left of the test as715the first argument, and return ``True`` or ``False``. Arguments passed716to the test are passed after the value.717718For example, the test ``{{ 42 is even }}`` is called behind the scenes719as ``is_even(42)``.720721Jinja comes with some :ref:`built-in tests <builtin-tests>`. To use a722custom tests, write a function that takes at least a ``value`` argument,723then register it in :attr:`Environment.tests`.724725Here's a test that checks if a value is a prime number:726727.. code-block:: python728729 import math730731 def is_prime(n):732 if n == 2:733 return True734735 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):736 if n % i == 0:737 return False738739 return True740741 environment.tests["prime"] = is_prime742743Now it can be used in templates:744745.. sourcecode:: jinja746747 {% if value is prime %}748 {{ value }} is a prime number749 {% else %}750 {{ value }} is not a prime number751 {% endif %}752753Some decorators are available to tell Jinja to pass extra information to754the filter. The object is passed as the first argument, making the value755being filtered the second argument.756Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 757–759why, one step back757- :func:`pass_environment` passes the :class:`Environment`.758- :func:`pass_eval_context` passes the :ref:`eval-context`.759- :func:`pass_context` passes the currentMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 760–762why, one step back760 :class:`~jinja2.runtime.Context`.761762Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 763–767why, one step back763.. _eval-context:764765Evaluation Context766------------------767Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 768–769why, one step back768The evaluation context (short eval context or eval ctx) makes it769possible to activate and deactivate compiled features at runtime.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 770why, one step back770Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 771–772why, one step back771Currently it is only used to enable and disable automatic escaping, but772it can be used by extensions as well.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 773why, one step back773Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 774–776why, one step back774The ``autoescape`` setting should be checked on the evaluation context,775not the environment. The evaluation context will have the computed value776for the current template.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 777why, one step back777Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 778why, one step back778Instead of ``pass_environment``:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 779why, one step back779Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 780–782why, one step back780.. code-block:: python781782 @pass_environmentMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 783–784why, one step back783 def filter(env, value):784 result = do_something(value)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 785why, one step back785Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 786–787why, one step back786 if env.autoescape:787 result = Markup(result)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 788why, one step back788Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 789–790why, one step back789 return result790Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 791why, one step back791Use ``pass_eval_context`` if you only need the setting:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 792why, one step back792Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 793–796why, one step back793.. code-block:: python794795 @pass_eval_context796 def filter(eval_ctx, value):Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 797why, one step back797 result = do_something(value)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 798–799why, one step back798799 if eval_ctx.autoescape:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 800why, one step back800 result = Markup(result)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 801why, one step back801Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 802–803why, one step back802 return result803Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 804–809why, one step back804Or use ``pass_context`` if you need other context behavior as well:805806.. code-block:: python807808 @pass_context809 def filter(context, value):Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 810why, one step back810 result = do_something(value)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 811–812why, one step back811812 if context.eval_ctx.autoescape:Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 813why, one step back813 result = Markup(result)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 814why, one step back814Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 815–821why, one step back815 return result816817The evaluation context must not be modified at runtime. Modifications818must only happen with a :class:`nodes.EvalContextModifier` and819:class:`nodes.ScopedEvalContextModifier` from an extension, not on the820eval context object itself.821Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 822why, one step back822.. autoclass:: jinja2.nodes.EvalContextMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 823–838why, one step back823824 .. attribute:: autoescape825826 `True` or `False` depending on if autoescaping is active or not.827828 .. attribute:: volatile829830 `True` if the compiler cannot evaluate some expressions at compile831 time. At runtime this should always be `False`.832833834.. _global-namespace:835836The Global Namespace837--------------------838Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 839–859why, one step back839The global namespace stores variables and functions that should be840available without needing to pass them to :meth:`Template.render`. They841are also available to templates that are imported or included without842context. Most applications should only use :attr:`Environment.globals`.843844:attr:`Environment.globals` are intended for data that is common to all845templates loaded by that environment. :attr:`Template.globals` are846intended for data that is common to all renders of that template, and847default to :attr:`Environment.globals` unless they're given in848:meth:`Environment.get_template`, etc. Data that is specific to a849render should be passed as context to :meth:`Template.render`.850851Only one set of globals is used during any specific rendering. If852templates A and B both have template globals, and B extends A, then853only B's globals are used for both when using ``b.render()``.854855Environment globals should not be changed after loading any templates,856and template globals should not be changed at any time after loading the857template. Changing globals after loading a template will result in858unexpected behavior as they may be shared between the environment and859other templates.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 860–885why, one step back860861862.. _low-level-api:863864Low Level API865-------------866867The low level API exposes functionality that can be useful to understand some868implementation details, debugging purposes or advanced :ref:`extension869<jinja-extensions>` techniques. Unless you know exactly what you are doing we870don't recommend using any of those.871872.. automethod:: Environment.lex873874.. automethod:: Environment.parse875876.. automethod:: Environment.preprocess877878.. automethod:: Template.new_context879880.. method:: Template.root_render_func(context)881882 This is the low level render function. It's passed a :class:`Context`883 that has to be created by :meth:`new_context` of the same template or884 a compatible template. This render function is generated by the885 compiler from the template code and returns a generator that yieldsMerge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 886why, one step back886 strings.Merge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
lines 887–919why, one step back887888 If an exception in the template code happens the template engine will889 not rewrite the exception but pass through the original one. As a890 matter of fact this function should only be called from within a891 :meth:`render` / :meth:`generate` / :meth:`stream` call.892893.. attribute:: Template.blocks894895 A dict of block render functions. Each of these functions works exactly896 like the :meth:`root_render_func` with the same limitations.897898.. attribute:: Template.is_up_to_date899900 This attribute is `False` if there is a newer version of the template901 available, otherwise `True`.902903.. admonition:: Note904905 The low-level API is fragile. Future Jinja versions will try not to906 change it in a backwards incompatible way but modifications in the Jinja907 core may shine through. For example if Jinja introduces a new AST node908 in later versions that may be returned by :meth:`~Environment.parse`.909910The Meta API911------------912913.. versionadded:: 2.2914915The meta API returns some information about abstract syntax trees that916could help applications to implement more advanced template concepts. All917the functions of the meta API operate on an abstract syntax tree as918returned by the :meth:`Environment.parse` method.919Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 920why, one step back920.. autofunction:: jinja2.meta.find_undeclared_variablesMerge pull request #1113 from pallets/namespace-loaderDavid Lordbefore adoption9176fbd
line 921why, one step back921Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
line 922why, one step back922.. autofunction:: jinja2.meta.find_referenced_templates