| 1 |
API |
| 2 |
=== |
| 3 |
|
| 4 |
.. module:: jinja2 |
| 5 |
:noindex: |
| 6 |
:synopsis: public Jinja API |
| 7 |
|
| 8 |
This document describes the API to Jinja and not the template language |
| 9 |
(for that, see :doc:`/templates`). It will be most useful as reference |
| 10 |
to those implementing the template interface to the application and not |
| 11 |
those who are creating Jinja templates. |
| 12 |
|
| 13 |
Basics |
| 14 |
------ |
| 15 |
|
| 16 |
Jinja uses a central object called the template :class:`Environment`. |
| 17 |
Instances of this class are used to store the configuration and global objects, |
| 18 |
and are used to load templates from the file system or other locations. |
| 19 |
Even if you are creating templates from strings by using the constructor of |
| 20 |
:class:`Template` class, an environment is created automatically for you, |
| 21 |
albeit a shared one. |
| 22 |
|
| 23 |
Most applications will create one :class:`Environment` object on application |
| 24 |
initialization and use that to load templates. In some cases however, it's |
| 25 |
useful to have multiple environments side by side, if different configurations |
| 26 |
are in use. |
| 27 |
|
| 28 |
The simplest way to configure Jinja to load templates for your |
| 29 |
application is to use :class:`~loaders.PackageLoader`. |
| 30 |
|
| 31 |
.. code-block:: python |
| 32 |
|
| 33 |
from jinja2 import Environment, PackageLoader, select_autoescape |
| 34 |
env = Environment( |
| 35 |
loader=PackageLoader("yourapp"), |
| 36 |
autoescape=select_autoescape() |
| 37 |
) |
| 38 |
|
| 39 |
This will create a template environment with a loader that looks up |
| 40 |
templates in the ``templates`` folder inside the ``yourapp`` Python |
| 41 |
package (or next to the ``yourapp.py`` Python module). It also enables |
| 42 |
autoescaping for HTML files. This loader only requires that ``yourapp`` |
| 43 |
is importable, it figures out the absolute path to the folder for you. |
| 44 |
|
| 45 |
Different loaders are available to load templates in other ways or from |
| 46 |
other locations. They're listed in the `Loaders`_ section below. You can |
| 47 |
also write your own if you want to load templates from a source that's |
| 48 |
more specialized to your project. |
| 49 |
|
| 50 |
To load a template from this environment, call the :meth:`get_template` |
| 51 |
method, which returns the loaded :class:`Template`. |
| 52 |
|
| 53 |
.. code-block:: python |
| 54 |
|
| 55 |
template = env.get_template("mytemplate.html") |
| 56 |
|
| 57 |
To render it with some variables, call the :meth:`render` method. |
| 58 |
|
| 59 |
.. code-block:: python |
| 60 |
|
| 61 |
print(template.render(the="variables", go="here")) |
| 62 |
|
| 63 |
Using a template loader rather than passing strings to :class:`Template` |
| 64 |
or :meth:`Environment.from_string` has multiple advantages. Besides being |
| 65 |
a lot easier to use it also enables template inheritance. |
| 66 |
|
| 67 |
.. admonition:: Notes on Autoescaping |
| 68 |
|
| 69 |
In future versions of Jinja we might enable autoescaping by default |
| 70 |
for security reasons. As such you are encouraged to explicitly |
| 71 |
configure autoescaping now instead of relying on the default. |
| 72 |
|
| 73 |
|
| 74 |
High Level API |
| 75 |
-------------- |
| 76 |
|
| 77 |
The high-level API is the API you will use in the application to load and |
| 78 |
render Jinja templates. The :ref:`low-level-api` on the other side is only |
| 79 |
useful if you want to dig deeper into Jinja or :ref:`develop extensions |
| 80 |
<jinja-extensions>`. |
| 81 |
|
| 82 |
.. 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_extension |
| 86 |
|
| 87 |
.. attribute:: shared |
| 88 |
|
| 89 |
If a template was created by using the :class:`Template` constructor |
| 90 |
an environment is created automatically. These environments are |
| 91 |
created as shared environments which means that multiple templates |
| 92 |
may have the same anonymous environment. For all shared environments |
| 93 |
this attribute is `True`, else `False`. |
| 94 |
|
| 95 |
.. attribute:: sandboxed |
| 96 |
|
| 97 |
If the environment is sandboxed this attribute is `True`. For the |
| 98 |
sandbox mode have a look at the documentation for the |
| 99 |
:class:`~jinja2.sandbox.SandboxedEnvironment`. |
| 100 |
|
| 101 |
.. attribute:: filters |
| 102 |
|
| 103 |
A dict of filters for this environment. As long as no template was |
| 104 |
loaded it's safe to add new filters or remove old. For custom filters |
| 105 |
see :ref:`writing-filters`. For valid filter names have a look at |
| 106 |
:ref:`identifier-naming`. |
| 107 |
|
| 108 |
.. attribute:: tests |
| 109 |
|
| 110 |
A dict of test functions for this environment. As long as no |
| 111 |
template was loaded it's safe to modify this dict. For custom tests |
| 112 |
see :ref:`writing-tests`. For valid test names have a look at |
| 113 |
:ref:`identifier-naming`. |
| 114 |
|
| 115 |
.. attribute:: globals |
| 116 |
|
| 117 |
A dict of variables that are available in every template loaded |
| 118 |
by the environment. As long as no template was loaded it's safe |
| 119 |
to modify this. For more details see :ref:`global-namespace`. |
| 120 |
For valid object names see :ref:`identifier-naming`. |
| 121 |
|
| 122 |
.. attribute:: policies |
| 123 |
|
| 124 |
A dictionary with :ref:`policies`. These can be reconfigured to |
| 125 |
change the runtime behavior or certain template features. Usually |
| 126 |
these are security related. |
| 127 |
|
| 128 |
.. attribute:: code_generator_class |
| 129 |
|
| 130 |
The class used for code generation. This should not be changed |
| 131 |
in most cases, unless you need to modify the Python code a |
| 132 |
template compiles to. |
| 133 |
|
| 134 |
.. attribute:: context_class |
| 135 |
|
| 136 |
The context used for templates. This should not be changed |
| 137 |
in most cases, unless you need to modify internals of how |
| 138 |
template variables are handled. For details, see |
| 139 |
:class:`~jinja2.runtime.Context`. |
| 140 |
|
| 141 |
.. automethod:: overlay([options]) |
| 142 |
|
| 143 |
.. method:: undefined([hint, obj, name, exc]) |
| 144 |
|
| 145 |
Creates a new :class:`Undefined` object for `name`. This is useful |
| 146 |
for filters or functions that may return undefined objects for |
| 147 |
some operations. All parameters except of `hint` should be provided |
| 148 |
as keyword parameters for better readability. The `hint` is used as |
| 149 |
error message for the exception if provided, otherwise the error |
| 150 |
message will be generated from `obj` and `name` automatically. The exception |
| 151 |
provided as `exc` is raised if something with the generated undefined |
| 152 |
object is done that the undefined object does not allow. The default |
| 153 |
exception is :exc:`UndefinedError`. If a `hint` is provided the |
| 154 |
`name` may be omitted. |
| 155 |
|
| 156 |
The most common way to create an undefined object is by providing |
| 157 |
a name only:: |
| 158 |
|
| 159 |
return environment.undefined(name='some_name') |
| 160 |
|
| 161 |
This means that the name `some_name` is not defined. If the name |
| 162 |
was from an attribute of an object it makes sense to tell the |
| 163 |
undefined object the holder object to improve the error message:: |
| 164 |
|
| 165 |
if not hasattr(obj, 'attr'): |
| 166 |
return environment.undefined(obj=obj, name='attr') |
| 167 |
|
| 168 |
For a more complex example you can provide a hint. For example |
| 169 |
the :func:`first` filter creates an undefined object that way:: |
| 170 |
|
| 171 |
return environment.undefined('no first item, sequence was empty') |
| 172 |
|
| 173 |
If it the `name` or `obj` is known (for example because an attribute |
| 174 |
was accessed) it should be passed to the undefined object, even if |
| 175 |
a custom `hint` is provided. This gives undefined objects the |
| 176 |
possibility to enhance the error message. |
| 177 |
|
| 178 |
.. autoclass:: Template |
| 179 |
:members: module, make_module |
| 180 |
|
| 181 |
.. attribute:: globals |
| 182 |
|
| 183 |
A dict of variables that are available every time the template |
| 184 |
is rendered, without needing to pass them during render. This |
| 185 |
should not be modified, as depending on how the template was |
| 186 |
loaded it may be shared with the environment and other |
| 187 |
templates. |
| 188 |
|
| 189 |
Defaults to :attr:`Environment.globals` unless extra values are |
| 190 |
passed to :meth:`Environment.get_template`. |
| 191 |
|
| 192 |
Globals are only intended for data that is common to every |
| 193 |
render of the template. Specific data should be passed to |
| 194 |
:meth:`render`. |
| 195 |
|
| 196 |
See :ref:`global-namespace`. |
| 197 |
|
| 198 |
.. attribute:: name |
| 199 |
|
| 200 |
The loading name of the template. If the template was loaded from a |
| 201 |
string this is `None`. |
| 202 |
|
| 203 |
.. attribute:: filename |
| 204 |
|
| 205 |
The filename of the template on the file system if it was loaded from |
| 206 |
there. Otherwise this is `None`. |
| 207 |
|
| 208 |
.. automethod:: render([context]) |
| 209 |
|
| 210 |
.. automethod:: generate([context]) |
| 211 |
|
| 212 |
.. automethod:: stream([context]) |
| 213 |
|
| 214 |
.. automethod:: render_async([context]) |
| 215 |
|
| 216 |
.. automethod:: generate_async([context]) |
| 217 |
|
| 218 |
|
| 219 |
.. autoclass:: jinja2.environment.TemplateStream() |
| 220 |
:members: disable_buffering, enable_buffering, dump |
| 221 |
|
| 222 |
|
| 223 |
Autoescaping |
| 224 |
------------ |
| 225 |
|
| 226 |
.. versionchanged:: 2.4 |
| 227 |
|
| 228 |
Jinja now comes with autoescaping support. As of Jinja 2.9 the |
| 229 |
autoescape extension is removed and built-in. However autoescaping is |
| 230 |
not yet enabled by default though this will most likely change in the |
| 231 |
future. It's recommended to configure a sensible default for |
| 232 |
autoescaping. This makes it possible to enable and disable autoescaping |
| 233 |
on a per-template basis (HTML versus text for instance). |
| 234 |
|
| 235 |
.. autofunction:: jinja2.select_autoescape |
| 236 |
|
| 237 |
Here a recommended setup that enables autoescaping for templates ending |
| 238 |
in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default |
| 239 |
for all other extensions. You can use the :func:`~jinja2.select_autoescape` |
| 240 |
function for this:: |
| 241 |
|
| 242 |
from jinja2 import Environment, PackageLoader, select_autoescape |
| 243 |
env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']), |
| 244 |
loader=PackageLoader('mypackage')) |
| 245 |
|
| 246 |
The :func:`~jinja.select_autoescape` function returns a function that |
| 247 |
works roughly like this:: |
| 248 |
|
| 249 |
def autoescape(template_name): |
| 250 |
if template_name is None: |
| 251 |
return False |
| 252 |
if template_name.endswith(('.html', '.htm', '.xml')) |
| 253 |
|
| 254 |
When implementing a guessing autoescape function, make sure you also |
| 255 |
accept `None` as valid template name. This will be passed when generating |
| 256 |
templates from strings. You should always configure autoescaping as |
| 257 |
defaults in the future might change. |
| 258 |
|
| 259 |
Inside the templates the behaviour can be temporarily changed by using |
| 260 |
the `autoescape` block (see :ref:`autoescape-overrides`). |
| 261 |
|
| 262 |
|
| 263 |
.. _identifier-naming: |
| 264 |
|
| 265 |
Notes on Identifiers |
| 266 |
-------------------- |
| 267 |
|
| 268 |
Jinja uses Python naming rules. Valid identifiers can be any combination |
| 269 |
of characters accepted by Python. |
| 270 |
|
| 271 |
Filters and tests are looked up in separate namespaces and have slightly |
| 272 |
modified identifier syntax. Filters and tests may contain dots to group |
| 273 |
filters and tests by topic. For example it's perfectly valid to add a |
| 274 |
function into the filter dict and call it `to.str`. The regular |
| 275 |
expression for filter and test identifiers is |
| 276 |
``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*``. |
| 277 |
|
| 278 |
|
| 279 |
Undefined Types |
| 280 |
--------------- |
| 281 |
|
| 282 |
These classes can be used as undefined types. The :class:`Environment` |
| 283 |
constructor takes an `undefined` parameter that can be one of those classes |
| 284 |
or a custom subclass of :class:`Undefined`. Whenever the template engine is |
| 285 |
unable to look up a name or access an attribute one of those objects is |
| 286 |
created and returned. Some operations on undefined values are then allowed, |
| 287 |
others fail. |
| 288 |
|
| 289 |
The closest to regular Python behavior is the :class:`StrictUndefined` which |
| 290 |
disallows all operations beside testing if it's an undefined object. |
| 291 |
|
| 292 |
.. autoclass:: jinja2.Undefined() |
| 293 |
|
| 294 |
.. attribute:: _undefined_hint |
| 295 |
|
| 296 |
Either `None` or a string with the error message for the |
| 297 |
undefined object. |
| 298 |
|
| 299 |
.. attribute:: _undefined_obj |
| 300 |
|
| 301 |
Either `None` or the owner object that caused the undefined object |
| 302 |
to be created (for example because an attribute does not exist). |
| 303 |
|
| 304 |
.. attribute:: _undefined_name |
| 305 |
|
| 306 |
The name for the undefined variable / attribute or just `None` |
| 307 |
if no such information exists. |
| 308 |
|
| 309 |
.. attribute:: _undefined_exception |
| 310 |
|
| 311 |
The exception that the undefined object wants to raise. This |
| 312 |
is usually one of :exc:`UndefinedError` or :exc:`SecurityError`. |
| 313 |
|
| 314 |
.. method:: _fail_with_undefined_error(\*args, \**kwargs) |
| 315 |
|
| 316 |
When called with any arguments this method raises |
| 317 |
:attr:`_undefined_exception` with an error message generated |
| 318 |
from the undefined hints stored on the undefined object. |
| 319 |
|
| 320 |
.. autoclass:: jinja2.ChainableUndefined() |
| 321 |
|
| 322 |
.. autoclass:: jinja2.DebugUndefined() |
| 323 |
|
| 324 |
.. autoclass:: jinja2.StrictUndefined() |
| 325 |
|
| 326 |
There is also a factory function that can decorate undefined objects to |
| 327 |
implement logging on failures: |
| 328 |
|
| 329 |
.. autofunction:: jinja2.make_logging_undefined |
| 330 |
|
| 331 |
Undefined objects are created by calling :attr:`undefined`. |
| 332 |
|
| 333 |
.. admonition:: Implementation |
| 334 |
|
| 335 |
:class:`Undefined` is implemented by overriding the special |
| 336 |
``__underscore__`` methods. For example the default |
| 337 |
:class:`Undefined` class implements ``__str__`` to returns an empty |
| 338 |
string, while ``__int__`` and others fail with an exception. To |
| 339 |
allow conversion to int by returning ``0`` you can implement your |
| 340 |
own subclass. |
| 341 |
|
| 342 |
.. code-block:: python |
| 343 |
|
| 344 |
class NullUndefined(Undefined): |
| 345 |
def __int__(self): |
| 346 |
return 0 |
| 347 |
|
| 348 |
def __float__(self): |
| 349 |
return 0.0 |
| 350 |
|
| 351 |
To disallow a method, override it and raise |
| 352 |
:attr:`~Undefined._undefined_exception`. Because this is very |
| 353 |
common there is the helper method |
| 354 |
:meth:`~Undefined._fail_with_undefined_error` that raises the error |
| 355 |
with the correct information. Here's a class that works like the |
| 356 |
regular :class:`Undefined` but fails on iteration:: |
| 357 |
|
| 358 |
class NonIterableUndefined(Undefined): |
| 359 |
def __iter__(self): |
| 360 |
self._fail_with_undefined_error() |
| 361 |
|
| 362 |
|
| 363 |
The Context |
| 364 |
----------- |
| 365 |
|
| 366 |
.. autoclass:: jinja2.runtime.Context() |
| 367 |
:members: get, resolve, resolve_or_missing, get_exported, get_all |
| 368 |
|
| 369 |
.. attribute:: parent |
| 370 |
|
| 371 |
A dict of read only, global variables the template looks up. These |
| 372 |
can either come from another :class:`Context`, from the |
| 373 |
:attr:`Environment.globals` or :attr:`Template.globals` or points |
| 374 |
to a dict created by combining the globals with the variables |
| 375 |
passed to the render function. It must not be altered. |
| 376 |
|
| 377 |
.. attribute:: vars |
| 378 |
|
| 379 |
The template local variables. This list contains environment and |
| 380 |
context functions from the :attr:`parent` scope as well as local |
| 381 |
modifications and exported variables from the template. The template |
| 382 |
will modify this dict during template evaluation but filters and |
| 383 |
context functions are not allowed to modify it. |
| 384 |
|
| 385 |
.. attribute:: environment |
| 386 |
|
| 387 |
The environment that loaded the template. |
| 388 |
|
| 389 |
.. attribute:: exported_vars |
| 390 |
|
| 391 |
This set contains all the names the template exports. The values for |
| 392 |
the names are in the :attr:`vars` dict. In order to get a copy of the |
| 393 |
exported variables as dict, :meth:`get_exported` can be used. |
| 394 |
|
| 395 |
.. attribute:: name |
| 396 |
|
| 397 |
The load name of the template owning this context. |
| 398 |
|
| 399 |
.. attribute:: blocks |
| 400 |
|
| 401 |
A dict with the current mapping of blocks in the template. The keys |
| 402 |
in this dict are the names of the blocks, and the values a list of |
| 403 |
blocks registered. The last item in each list is the current active |
| 404 |
block (latest in the inheritance chain). |
| 405 |
|
| 406 |
.. attribute:: eval_ctx |
| 407 |
|
| 408 |
The current :ref:`eval-context`. |
| 409 |
|
| 410 |
.. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs) |
| 411 |
|
| 412 |
|
| 413 |
The context is immutable, it prevents modifications, and if it is |
| 414 |
modified somehow despite that those changes may not show up. For |
| 415 |
performance, Jinja does not use the context as data storage for, only as |
| 416 |
a primary data source. Variables that the template does not define are |
| 417 |
looked up in the context, but variables the template does define are |
| 418 |
stored locally. |
| 419 |
|
| 420 |
Instead of modifying the context directly, a function should return |
| 421 |
a value that can be assigned to a variable within the template itself. |
| 422 |
|
| 423 |
.. code-block:: jinja |
| 424 |
|
| 425 |
{% set comments = get_latest_comments() %} |
| 426 |
|
| 427 |
|
| 428 |
.. _loaders: |
| 429 |
|
| 430 |
Loaders |
| 431 |
------- |
| 432 |
|
| 433 |
Loaders are responsible for loading templates from a resource such as the |
| 434 |
file system. The environment will keep the compiled modules in memory like |
| 435 |
Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in |
| 436 |
size by default and templates are automatically reloaded. |
| 437 |
All loaders are subclasses of :class:`BaseLoader`. If you want to create your |
| 438 |
own loader, subclass :class:`BaseLoader` and override `get_source`. |
| 439 |
|
| 440 |
.. autoclass:: jinja2.BaseLoader |
| 441 |
:members: get_source, load |
| 442 |
|
| 443 |
Here a list of the builtin loaders Jinja provides: |
| 444 |
|
| 445 |
.. autoclass:: jinja2.FileSystemLoader |
| 446 |
|
| 447 |
.. autoclass:: jinja2.PackageLoader |
| 448 |
|
| 449 |
.. autoclass:: jinja2.DictLoader |
| 450 |
|
| 451 |
.. autoclass:: jinja2.FunctionLoader |
| 452 |
|
| 453 |
.. autoclass:: jinja2.PrefixLoader |
| 454 |
|
| 455 |
.. autoclass:: jinja2.ChoiceLoader |
| 456 |
|
| 457 |
.. autoclass:: jinja2.ModuleLoader |
| 458 |
|
| 459 |
|
| 460 |
.. _bytecode-cache: |
| 461 |
|
| 462 |
Bytecode Cache |
| 463 |
-------------- |
| 464 |
|
| 465 |
Jinja 2.1 and higher support external bytecode caching. Bytecode caches make |
| 466 |
it possible to store the generated bytecode on the file system or a different |
| 467 |
location to avoid parsing the templates on first use. |
| 468 |
|
| 469 |
This is especially useful if you have a web application that is initialized on |
| 470 |
the first request and Jinja compiles many templates at once which slows down |
| 471 |
the application. |
| 472 |
|
| 473 |
To use a bytecode cache, instantiate it and pass it to the :class:`Environment`. |
| 474 |
|
| 475 |
.. autoclass:: jinja2.BytecodeCache |
| 476 |
:members: load_bytecode, dump_bytecode, clear |
| 477 |
|
| 478 |
.. autoclass:: jinja2.bccache.Bucket |
| 479 |
:members: write_bytecode, load_bytecode, bytecode_from_string, |
| 480 |
bytecode_to_string, reset |
| 481 |
|
| 482 |
.. attribute:: environment |
| 483 |
|
| 484 |
The :class:`Environment` that created the bucket. |
| 485 |
|
| 486 |
.. attribute:: key |
| 487 |
|
| 488 |
The unique cache key for this bucket |
| 489 |
|
| 490 |
.. attribute:: code |
| 491 |
|
| 492 |
The bytecode if it's loaded, otherwise `None`. |
| 493 |
|
| 494 |
|
| 495 |
Builtin bytecode caches: |
| 496 |
|
| 497 |
.. autoclass:: jinja2.FileSystemBytecodeCache |
| 498 |
|
| 499 |
.. autoclass:: jinja2.MemcachedBytecodeCache |
| 500 |
|
| 501 |
|
| 502 |
Async Support |
| 503 |
------------- |
| 504 |
|
| 505 |
.. versionadded:: 2.9 |
| 506 |
|
| 507 |
Jinja supports the Python ``async`` and ``await`` syntax. For the |
| 508 |
template designer, this support (when enabled) is entirely transparent, |
| 509 |
templates continue to look exactly the same. However, developers should |
| 510 |
be aware of the implementation as it affects what types of APIs you can |
| 511 |
use. |
| 512 |
|
| 513 |
By default, async support is disabled. Enabling it will cause the |
| 514 |
environment to compile different code behind the scenes in order to |
| 515 |
handle async and sync code in an asyncio event loop. This has the |
| 516 |
following implications: |
| 517 |
|
| 518 |
- The compiled code uses ``await`` for functions and attributes, and |
| 519 |
uses ``async for`` loops. In order to support using both async and |
| 520 |
sync functions in this context, a small wrapper is placed around |
| 521 |
all calls and access, which adds overhead compared to purely async |
| 522 |
code. |
| 523 |
- Sync methods and filters become wrappers around their corresponding |
| 524 |
async implementations where needed. For example, ``render`` invokes |
| 525 |
``async_render``, and ``|map`` supports async iterables. |
| 526 |
|
| 527 |
Awaitable objects can be returned from functions in templates and any |
| 528 |
function call in a template will automatically await the result. The |
| 529 |
``await`` you would normally add in Python is implied. For example, you |
| 530 |
can provide a method that asynchronously loads data from a database, and |
| 531 |
from the template designer's point of view it can be called like any |
| 532 |
other function. |
| 533 |
|
| 534 |
|
| 535 |
.. _policies: |
| 536 |
|
| 537 |
Policies |
| 538 |
-------- |
| 539 |
|
| 540 |
Starting with Jinja 2.9 policies can be configured on the environment |
| 541 |
which can slightly influence how filters and other template constructs |
| 542 |
behave. They can be configured with the |
| 543 |
:attr:`~jinja2.Environment.policies` attribute. |
| 544 |
|
| 545 |
Example:: |
| 546 |
|
| 547 |
env.policies['urlize.rel'] = 'nofollow noopener' |
| 548 |
|
| 549 |
``truncate.leeway``: |
| 550 |
Configures the leeway default for the `truncate` filter. Leeway as |
| 551 |
introduced in 2.9 but to restore compatibility with older templates |
| 552 |
it can be configured to `0` to get the old behavior back. The default |
| 553 |
is `5`. |
| 554 |
|
| 555 |
``urlize.rel``: |
| 556 |
A string that defines the items for the `rel` attribute of generated |
| 557 |
links with the `urlize` filter. These items are always added. The |
| 558 |
default is `noopener`. |
| 559 |
|
| 560 |
``urlize.target``: |
| 561 |
The default target that is issued for links from the `urlize` filter |
| 562 |
if no other target is defined by the call explicitly. |
| 563 |
|
| 564 |
``urlize.extra_schemes``: |
| 565 |
Recognize URLs that start with these schemes in addition to the |
| 566 |
default ``http://``, ``https://``, and ``mailto:``. |
| 567 |
|
| 568 |
``json.dumps_function``: |
| 569 |
If this is set to a value other than `None` then the `tojson` filter |
| 570 |
will dump with this function instead of the default one. Note that |
| 571 |
this function should accept arbitrary extra arguments which might be |
| 572 |
passed in the future from the filter. Currently the only argument |
| 573 |
that might be passed is `indent`. The default dump function is |
| 574 |
``json.dumps``. |
| 575 |
|
| 576 |
``json.dumps_kwargs``: |
| 577 |
Keyword arguments to be passed to the dump function. The default is |
| 578 |
``{'sort_keys': True}``. |
| 579 |
|
| 580 |
.. _ext-i18n-trimmed: |
| 581 |
|
| 582 |
``ext.i18n.trimmed``: |
| 583 |
If this is set to `True`, ``{% trans %}`` blocks of the |
| 584 |
:ref:`i18n-extension` will always unify linebreaks and surrounding |
| 585 |
whitespace as if the `trimmed` modifier was used. |
| 586 |
|
| 587 |
|
| 588 |
Utilities |
| 589 |
--------- |
| 590 |
|
| 591 |
These helper functions and classes are useful if you add custom filters or |
| 592 |
functions to a Jinja environment. |
| 593 |
|
| 594 |
.. autofunction:: jinja2.pass_context |
| 595 |
|
| 596 |
.. autofunction:: jinja2.pass_eval_context |
| 597 |
|
| 598 |
.. autofunction:: jinja2.pass_environment |
| 599 |
|
| 600 |
.. autofunction:: jinja2.clear_caches |
| 601 |
|
| 602 |
.. autofunction:: jinja2.is_undefined |
| 603 |
|
| 604 |
|
| 605 |
Exceptions |
| 606 |
---------- |
| 607 |
|
| 608 |
.. autoexception:: jinja2.TemplateError |
| 609 |
|
| 610 |
.. autoexception:: jinja2.UndefinedError |
| 611 |
|
| 612 |
.. autoexception:: jinja2.TemplateNotFound |
| 613 |
|
| 614 |
.. autoexception:: jinja2.TemplatesNotFound |
| 615 |
|
| 616 |
.. autoexception:: jinja2.TemplateSyntaxError |
| 617 |
|
| 618 |
.. attribute:: message |
| 619 |
|
| 620 |
The error message. |
| 621 |
|
| 622 |
.. attribute:: lineno |
| 623 |
|
| 624 |
The line number where the error occurred. |
| 625 |
|
| 626 |
.. attribute:: name |
| 627 |
|
| 628 |
The load name for the template. |
| 629 |
|
| 630 |
.. attribute:: filename |
| 631 |
|
| 632 |
The filename that loaded the template in the encoding of the |
| 633 |
file system (most likely utf-8, or mbcs on Windows systems). |
| 634 |
|
| 635 |
.. autoexception:: jinja2.TemplateRuntimeError |
| 636 |
|
| 637 |
.. autoexception:: jinja2.TemplateAssertionError |
| 638 |
|
| 639 |
|
| 640 |
.. _writing-filters: |
| 641 |
|
| 642 |
Custom Filters |
| 643 |
-------------- |
| 644 |
|
| 645 |
Filters are Python functions that take the value to the left of the |
| 646 |
filter as the first argument and produce a new value. Arguments passed |
| 647 |
to the filter are passed after the value. |
| 648 |
|
| 649 |
For example, the filter ``{{ 42|myfilter(23) }}`` is called behind the |
| 650 |
scenes as ``myfilter(42, 23)``. |
| 651 |
|
| 652 |
Jinja comes with some :ref:`built-in filters <builtin-filters>`. To use |
| 653 |
a custom filter, write a function that takes at least a ``value`` |
| 654 |
argument, then register it in :attr:`Environment.filters`. |
| 655 |
|
| 656 |
Here's a filter that formats datetime objects: |
| 657 |
|
| 658 |
.. code-block:: python |
| 659 |
|
| 660 |
def datetime_format(value, format="%H:%M %d-%m-%y"): |
| 661 |
return value.strftime(format) |
| 662 |
|
| 663 |
environment.filters["datetime_format"] = datetime_format |
| 664 |
|
| 665 |
Now it can be used in templates: |
| 666 |
|
| 667 |
.. sourcecode:: jinja |
| 668 |
|
| 669 |
{{ article.pub_date|datetime_format }} |
| 670 |
{{ article.pub_date|datetime_format("%B %Y") }} |
| 671 |
|
| 672 |
Some decorators are available to tell Jinja to pass extra information to |
| 673 |
the filter. The object is passed as the first argument, making the value |
| 674 |
being filtered the second argument. |
| 675 |
|
| 676 |
- :func:`pass_environment` passes the :class:`Environment`. |
| 677 |
- :func:`pass_eval_context` passes the :ref:`eval-context`. |
| 678 |
- :func:`pass_context` passes the current |
| 679 |
:class:`~jinja2.runtime.Context`. |
| 680 |
|
| 681 |
Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>`` |
| 682 |
tags. It uses the eval context to check if autoescape is currently |
| 683 |
enabled before escaping the input and marking the output safe. |
| 684 |
|
| 685 |
.. code-block:: python |
| 686 |
|
| 687 |
import re |
| 688 |
from jinja2 import pass_eval_context |
| 689 |
from markupsafe import Markup, escape |
| 690 |
|
| 691 |
@pass_eval_context |
| 692 |
def nl2br(eval_ctx, value): |
| 693 |
br = "<br>\n" |
| 694 |
|
| 695 |
if eval_ctx.autoescape: |
| 696 |
value = escape(value) |
| 697 |
br = Markup(br) |
| 698 |
|
| 699 |
result = "\n\n".join( |
| 700 |
f"<p>{br.join(p.splitlines())}<\p>" |
| 701 |
for p in re.split(r"(?:\r\n|\r(?!\n)|\n){2,}", value) |
| 702 |
) |
| 703 |
return Markup(result) if autoescape else result |
| 704 |
|
| 705 |
|
| 706 |
.. _writing-tests: |
| 707 |
|
| 708 |
Custom Tests |
| 709 |
------------ |
| 710 |
|
| 711 |
Test are Python functions that take the value to the left of the test as |
| 712 |
the first argument, and return ``True`` or ``False``. Arguments passed |
| 713 |
to the test are passed after the value. |
| 714 |
|
| 715 |
For example, the test ``{{ 42 is even }}`` is called behind the scenes |
| 716 |
as ``is_even(42)``. |
| 717 |
|
| 718 |
Jinja comes with some :ref:`built-in tests <builtin-tests>`. To use a |
| 719 |
custom tests, write a function that takes at least a ``value`` argument, |
| 720 |
then register it in :attr:`Environment.tests`. |
| 721 |
|
| 722 |
Here's a test that checks if a value is a prime number: |
| 723 |
|
| 724 |
.. code-block:: python |
| 725 |
|
| 726 |
import math |
| 727 |
|
| 728 |
def is_prime(n): |
| 729 |
if n == 2: |
| 730 |
return True |
| 731 |
|
| 732 |
for i in range(2, int(math.ceil(math.sqrt(n))) + 1): |
| 733 |
if n % i == 0: |
| 734 |
return False |
| 735 |
|
| 736 |
return True |
| 737 |
|
| 738 |
environment.tests["prime"] = is_prime |
| 739 |
|
| 740 |
Now it can be used in templates: |
| 741 |
|
| 742 |
.. sourcecode:: jinja |
| 743 |
|
| 744 |
{% if value is prime %} |
| 745 |
{{ value }} is a prime number |
| 746 |
{% else %} |
| 747 |
{{ value }} is not a prime number |
| 748 |
{% endif %} |
| 749 |
|
| 750 |
Some decorators are available to tell Jinja to pass extra information to |
| 751 |
the test. The object is passed as the first argument, making the value |
| 752 |
being tested the second argument. |
| 753 |
|
| 754 |
- :func:`pass_environment` passes the :class:`Environment`. |
| 755 |
- :func:`pass_eval_context` passes the :ref:`eval-context`. |
| 756 |
- :func:`pass_context` passes the current |
| 757 |
:class:`~jinja2.runtime.Context`. |
| 758 |
|
| 759 |
|
| 760 |
.. _eval-context: |
| 761 |
|
| 762 |
Evaluation Context |
| 763 |
------------------ |
| 764 |
|
| 765 |
The evaluation context (short eval context or eval ctx) makes it |
| 766 |
possible to activate and deactivate compiled features at runtime. |
| 767 |
|
| 768 |
Currently it is only used to enable and disable automatic escaping, but |
| 769 |
it can be used by extensions as well. |
| 770 |
|
| 771 |
The ``autoescape`` setting should be checked on the evaluation context, |
| 772 |
not the environment. The evaluation context will have the computed value |
| 773 |
for the current template. |
| 774 |
|
| 775 |
Instead of ``pass_environment``: |
| 776 |
|
| 777 |
.. code-block:: python |
| 778 |
|
| 779 |
@pass_environment |
| 780 |
def filter(env, value): |
| 781 |
result = do_something(value) |
| 782 |
|
| 783 |
if env.autoescape: |
| 784 |
result = Markup(result) |
| 785 |
|
| 786 |
return result |
| 787 |
|
| 788 |
Use ``pass_eval_context`` if you only need the setting: |
| 789 |
|
| 790 |
.. code-block:: python |
| 791 |
|
| 792 |
@pass_eval_context |
| 793 |
def filter(eval_ctx, value): |
| 794 |
result = do_something(value) |
| 795 |
|
| 796 |
if eval_ctx.autoescape: |
| 797 |
result = Markup(result) |
| 798 |
|
| 799 |
return result |
| 800 |
|
| 801 |
Or use ``pass_context`` if you need other context behavior as well: |
| 802 |
|
| 803 |
.. code-block:: python |
| 804 |
|
| 805 |
@pass_context |
| 806 |
def filter(context, value): |
| 807 |
result = do_something(value) |
| 808 |
|
| 809 |
if context.eval_ctx.autoescape: |
| 810 |
result = Markup(result) |
| 811 |
|
| 812 |
return result |
| 813 |
|
| 814 |
The evaluation context must not be modified at runtime. Modifications |
| 815 |
must only happen with a :class:`nodes.EvalContextModifier` and |
| 816 |
:class:`nodes.ScopedEvalContextModifier` from an extension, not on the |
| 817 |
eval context object itself. |
| 818 |
|
| 819 |
.. autoclass:: jinja2.nodes.EvalContext |
| 820 |
|
| 821 |
.. attribute:: autoescape |
| 822 |
|
| 823 |
`True` or `False` depending on if autoescaping is active or not. |
| 824 |
|
| 825 |
.. attribute:: volatile |
| 826 |
|
| 827 |
`True` if the compiler cannot evaluate some expressions at compile |
| 828 |
time. At runtime this should always be `False`. |
| 829 |
|
| 830 |
|
| 831 |
.. _global-namespace: |
| 832 |
|
| 833 |
The Global Namespace |
| 834 |
-------------------- |
| 835 |
|
| 836 |
The global namespace stores variables and functions that should be |
| 837 |
available without needing to pass them to :meth:`Template.render`. They |
| 838 |
are also available to templates that are imported or included without |
| 839 |
context. Most applications should only use :attr:`Environment.globals`. |
| 840 |
|
| 841 |
:attr:`Environment.globals` are intended for data that is common to all |
| 842 |
templates loaded by that environment. :attr:`Template.globals` are |
| 843 |
intended for data that is common to all renders of that template, and |
| 844 |
default to :attr:`Environment.globals` unless they're given in |
| 845 |
:meth:`Environment.get_template`, etc. Data that is specific to a |
| 846 |
render should be passed as context to :meth:`Template.render`. |
| 847 |
|
| 848 |
Only one set of globals is used during any specific rendering. If |
| 849 |
templates A and B both have template globals, and B extends A, then |
| 850 |
only B's globals are used for both when using ``b.render()``. |
| 851 |
|
| 852 |
Environment globals should not be changed after loading any templates, |
| 853 |
and template globals should not be changed at any time after loading the |
| 854 |
template. Changing globals after loading a template will result in |
| 855 |
unexpected behavior as they may be shared between the environment and |
| 856 |
other templates. |
| 857 |
|
| 858 |
|
| 859 |
.. _low-level-api: |
| 860 |
|
| 861 |
Low Level API |
| 862 |
------------- |
| 863 |
|
| 864 |
The low level API exposes functionality that can be useful to understand some |
| 865 |
implementation details, debugging purposes or advanced :ref:`extension |
| 866 |
<jinja-extensions>` techniques. Unless you know exactly what you are doing we |
| 867 |
don't recommend using any of those. |
| 868 |
|
| 869 |
.. automethod:: Environment.lex |
| 870 |
|
| 871 |
.. automethod:: Environment.parse |
| 872 |
|
| 873 |
.. automethod:: Environment.preprocess |
| 874 |
|
| 875 |
.. automethod:: Template.new_context |
| 876 |
|
| 877 |
.. method:: Template.root_render_func(context) |
| 878 |
|
| 879 |
This is the low level render function. It's passed a :class:`Context` |
| 880 |
that has to be created by :meth:`new_context` of the same template or |
| 881 |
a compatible template. This render function is generated by the |
| 882 |
compiler from the template code and returns a generator that yields |
| 883 |
strings. |
| 884 |
|
| 885 |
If an exception in the template code happens the template engine will |
| 886 |
not rewrite the exception but pass through the original one. As a |
| 887 |
matter of fact this function should only be called from within a |
| 888 |
:meth:`render` / :meth:`generate` / :meth:`stream` call. |
| 889 |
|
| 890 |
.. attribute:: Template.blocks |
| 891 |
|
| 892 |
A dict of block render functions. Each of these functions works exactly |
| 893 |
like the :meth:`root_render_func` with the same limitations. |
| 894 |
|
| 895 |
.. attribute:: Template.is_up_to_date |
| 896 |
|
| 897 |
This attribute is `False` if there is a newer version of the template |
| 898 |
available, otherwise `True`. |
| 899 |
|
| 900 |
.. admonition:: Note |
| 901 |
|
| 902 |
The low-level API is fragile. Future Jinja versions will try not to |
| 903 |
change it in a backwards incompatible way but modifications in the Jinja |
| 904 |
core may shine through. For example if Jinja introduces a new AST node |
| 905 |
in later versions that may be returned by :meth:`~Environment.parse`. |
| 906 |
|
| 907 |
The Meta API |
| 908 |
------------ |
| 909 |
|
| 910 |
.. versionadded:: 2.2 |
| 911 |
|
| 912 |
The meta API returns some information about abstract syntax trees that |
| 913 |
could help applications to implement more advanced template concepts. All |
| 914 |
the functions of the meta API operate on an abstract syntax tree as |
| 915 |
returned by the :meth:`Environment.parse` method. |
| 916 |
|
| 917 |
.. autofunction:: jinja2.meta.find_undeclared_variables |
| 918 |
|
| 919 |
.. autofunction:: jinja2.meta.find_referenced_templates |