| 1 |
.. py:currentmodule:: jinja2 |
| 2 |
.. highlight:: html+jinja |
| 3 |
|
| 4 |
Template Designer Documentation |
| 5 |
=============================== |
| 6 |
|
| 7 |
This document describes the syntax and semantics of the template engine and |
| 8 |
will be most useful as reference to those creating Jinja templates. As the |
| 9 |
template engine is very flexible, the configuration from the application can |
| 10 |
be slightly different from the code presented here in terms of delimiters and |
| 11 |
behavior of undefined values. |
| 12 |
|
| 13 |
|
| 14 |
Synopsis |
| 15 |
-------- |
| 16 |
|
| 17 |
A Jinja template is simply a text file. Jinja can generate any text-based |
| 18 |
format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a |
| 19 |
specific extension: ``.html``, ``.xml``, or any other extension is just fine. |
| 20 |
|
| 21 |
A template contains **variables** and/or **expressions**, which get replaced |
| 22 |
with values when a template is *rendered*; and **tags**, which control the |
| 23 |
logic of the template. The template syntax is heavily inspired by Django and |
| 24 |
Python. |
| 25 |
|
| 26 |
Below is a minimal template that illustrates a few basics using the default |
| 27 |
Jinja configuration. We will cover the details later in this document:: |
| 28 |
|
| 29 |
<!DOCTYPE html> |
| 30 |
<html lang="en"> |
| 31 |
<head> |
| 32 |
<title>My Webpage</title> |
| 33 |
</head> |
| 34 |
<body> |
| 35 |
<ul id="navigation"> |
| 36 |
{% for item in navigation %} |
| 37 |
<li><a href="{{ item.href }}">{{ item.caption }}</a></li> |
| 38 |
{% endfor %} |
| 39 |
</ul> |
| 40 |
|
| 41 |
<h1>My Webpage</h1> |
| 42 |
{{ a_variable }} |
| 43 |
|
| 44 |
{# a comment #} |
| 45 |
</body> |
| 46 |
</html> |
| 47 |
|
| 48 |
The following example shows the default configuration settings. An application |
| 49 |
developer can change the syntax configuration from ``{% foo %}`` to ``<% foo |
| 50 |
%>``, or something similar. |
| 51 |
|
| 52 |
There are a few kinds of delimiters. The default Jinja delimiters are |
| 53 |
configured as follows: |
| 54 |
|
| 55 |
* ``{% ... %}`` for :ref:`Statements <list-of-control-structures>` |
| 56 |
* ``{{ ... }}`` for :ref:`Expressions` to print to the template output |
| 57 |
* ``{# ... #}`` for :ref:`Comments` not included in the template output |
| 58 |
|
| 59 |
:ref:`Line Statements and Comments <line-statements>` are also possible, |
| 60 |
though they don't have default prefix characters. To use them, set |
| 61 |
``line_statement_prefix`` and ``line_comment_prefix`` when creating the |
| 62 |
:class:`~jinja2.Environment`. |
| 63 |
|
| 64 |
|
| 65 |
Template File Extension |
| 66 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 67 |
|
| 68 |
As stated above, any file can be loaded as a template, regardless of |
| 69 |
file extension. Adding a ``.jinja`` extension, like ``user.html.jinja`` |
| 70 |
may make it easier for some IDEs or editor plugins, but is not required. |
| 71 |
Autoescaping, introduced later, can be applied based on file extension, |
| 72 |
so you'll need to take the extra suffix into account in that case. |
| 73 |
|
| 74 |
Another good heuristic for identifying templates is that they are in a |
| 75 |
``templates`` folder, regardless of extension. This is a common layout |
| 76 |
for projects. |
| 77 |
|
| 78 |
|
| 79 |
.. _variables: |
| 80 |
|
| 81 |
Variables |
| 82 |
--------- |
| 83 |
|
| 84 |
Template variables are defined by the context dictionary passed to the |
| 85 |
template. |
| 86 |
|
| 87 |
You can mess around with the variables in templates provided they are passed in |
| 88 |
by the application. Variables may have attributes or elements on them you can |
| 89 |
access too. What attributes a variable has depends heavily on the application |
| 90 |
providing that variable. |
| 91 |
|
| 92 |
You can use a dot (``.``) to access attributes of a variable in addition |
| 93 |
to the standard Python ``__getitem__`` "subscript" syntax (``[]``). |
| 94 |
|
| 95 |
The following lines do the same thing:: |
| 96 |
|
| 97 |
{{ foo.bar }} |
| 98 |
{{ foo['bar'] }} |
| 99 |
|
| 100 |
It's important to know that the outer double-curly braces are *not* part of the |
| 101 |
variable, but the print statement. If you access variables inside tags don't |
| 102 |
put the braces around them. |
| 103 |
|
| 104 |
If a variable or attribute does not exist, you will get back an undefined |
| 105 |
value. What you can do with that kind of value depends on the application |
| 106 |
configuration: the default behavior is to evaluate to an empty string if |
| 107 |
printed or iterated over, and to fail for every other operation. |
| 108 |
|
| 109 |
.. _notes-on-subscriptions: |
| 110 |
|
| 111 |
.. admonition:: Implementation |
| 112 |
|
| 113 |
For the sake of convenience, ``foo.bar`` in Jinja does the following |
| 114 |
things on the Python layer: |
| 115 |
|
| 116 |
- check for an attribute called `bar` on `foo` |
| 117 |
(``getattr(foo, 'bar')``) |
| 118 |
- if there is not, check for an item ``'bar'`` in `foo` |
| 119 |
(``foo.__getitem__('bar')``) |
| 120 |
- if there is not, return an undefined object. |
| 121 |
|
| 122 |
``foo['bar']`` works mostly the same with a small difference in sequence: |
| 123 |
|
| 124 |
- check for an item ``'bar'`` in `foo`. |
| 125 |
(``foo.__getitem__('bar')``) |
| 126 |
- if there is not, check for an attribute called `bar` on `foo`. |
| 127 |
(``getattr(foo, 'bar')``) |
| 128 |
- if there is not, return an undefined object. |
| 129 |
|
| 130 |
This is important if an object has an item and attribute with the same |
| 131 |
name. Additionally, the :func:`attr` filter only looks up attributes. |
| 132 |
|
| 133 |
.. _filters: |
| 134 |
|
| 135 |
Filters |
| 136 |
------- |
| 137 |
|
| 138 |
Variables can be modified by **filters**. Filters are separated from the |
| 139 |
variable by a pipe symbol (``|``) and may have optional arguments in |
| 140 |
parentheses. Multiple filters can be chained. The output of one filter is |
| 141 |
applied to the next. |
| 142 |
|
| 143 |
For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from |
| 144 |
variable `name` and title-case the output (``title(striptags(name))``). |
| 145 |
|
| 146 |
Filters that accept arguments have parentheses around the arguments, just like |
| 147 |
a function call. For example: ``{{ listx|join(', ') }}`` will join a list with |
| 148 |
commas (``str.join(', ', listx)``). |
| 149 |
|
| 150 |
The :ref:`builtin-filters` below describes all the builtin filters. |
| 151 |
|
| 152 |
.. _tests: |
| 153 |
|
| 154 |
Tests |
| 155 |
----- |
| 156 |
|
| 157 |
Beside filters, there are also so-called "tests" available. Tests can be used |
| 158 |
to test a variable against a common expression. To test a variable or |
| 159 |
expression, you add `is` plus the name of the test after the variable. For |
| 160 |
example, to find out if a variable is defined, you can do ``name is defined``, |
| 161 |
which will then return true or false depending on whether `name` is defined |
| 162 |
in the current template context. |
| 163 |
|
| 164 |
Tests can accept arguments, too. If the test only takes one argument, you can |
| 165 |
leave out the parentheses. For example, the following two |
| 166 |
expressions do the same thing:: |
| 167 |
|
| 168 |
{% if loop.index is divisibleby 3 %} |
| 169 |
{% if loop.index is divisibleby(3) %} |
| 170 |
|
| 171 |
The :ref:`builtin-tests` below describes all the builtin tests. |
| 172 |
|
| 173 |
|
| 174 |
.. _comments: |
| 175 |
|
| 176 |
Comments |
| 177 |
-------- |
| 178 |
|
| 179 |
To comment-out part of a line in a template, use the comment syntax which is |
| 180 |
by default set to ``{# ... #}``. This is useful to comment out parts of the |
| 181 |
template for debugging or to add information for other template designers or |
| 182 |
yourself:: |
| 183 |
|
| 184 |
{# note: commented-out template because we no longer use this |
| 185 |
{% for user in users %} |
| 186 |
... |
| 187 |
{% endfor %} |
| 188 |
#} |
| 189 |
|
| 190 |
|
| 191 |
Whitespace Control |
| 192 |
------------------ |
| 193 |
|
| 194 |
In the default configuration: |
| 195 |
|
| 196 |
* a single trailing newline is stripped if present |
| 197 |
* other whitespace (spaces, tabs, newlines etc.) is returned unchanged |
| 198 |
|
| 199 |
If an application configures Jinja to `trim_blocks`, the first newline after a |
| 200 |
template tag is removed automatically (like in PHP). The `lstrip_blocks` |
| 201 |
option can also be set to strip tabs and spaces from the beginning of a |
| 202 |
line to the start of a block. (Nothing will be stripped if there are |
| 203 |
other characters before the start of the block.) |
| 204 |
|
| 205 |
With both ``trim_blocks`` and ``lstrip_blocks`` disabled (the default), block |
| 206 |
tags on their own lines will be removed, but a blank line will remain and the |
| 207 |
spaces in the content will be preserved. For example, this template: |
| 208 |
|
| 209 |
.. code-block:: jinja |
| 210 |
|
| 211 |
<div> |
| 212 |
{% if True %} |
| 213 |
yay |
| 214 |
{% endif %} |
| 215 |
</div> |
| 216 |
|
| 217 |
With both ``trim_blocks`` and ``lstrip_blocks`` disabled, the template is |
| 218 |
rendered with blank lines inside the div: |
| 219 |
|
| 220 |
.. code-block:: text |
| 221 |
|
| 222 |
<div> |
| 223 |
|
| 224 |
yay |
| 225 |
|
| 226 |
</div> |
| 227 |
|
| 228 |
With both ``trim_blocks`` and ``lstrip_blocks`` enabled, the template block |
| 229 |
lines are completely removed: |
| 230 |
|
| 231 |
.. code-block:: text |
| 232 |
|
| 233 |
<div> |
| 234 |
yay |
| 235 |
</div> |
| 236 |
|
| 237 |
You can manually disable the `lstrip_blocks` behavior by putting a |
| 238 |
plus sign (``+``) at the start of a block:: |
| 239 |
|
| 240 |
<div> |
| 241 |
{%+ if something %}yay{% endif %} |
| 242 |
</div> |
| 243 |
|
| 244 |
Similarly, you can manually disable the ``trim_blocks`` behavior by |
| 245 |
putting a plus sign (``+``) at the end of a block:: |
| 246 |
|
| 247 |
<div> |
| 248 |
{% if something +%} |
| 249 |
yay |
| 250 |
{% endif %} |
| 251 |
</div> |
| 252 |
|
| 253 |
You can also strip whitespace in templates by hand. If you add a minus |
| 254 |
sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a |
| 255 |
comment, or a variable expression, the whitespaces before or after |
| 256 |
that block will be removed:: |
| 257 |
|
| 258 |
{% for item in seq -%} |
| 259 |
{{ item }} |
| 260 |
{%- endfor %} |
| 261 |
|
| 262 |
This will yield all elements without whitespace between them. If `seq` was |
| 263 |
a list of numbers from ``1`` to ``9``, the output would be ``123456789``. |
| 264 |
|
| 265 |
If :ref:`line-statements` are enabled, they strip leading whitespace |
| 266 |
automatically up to the beginning of the line. |
| 267 |
|
| 268 |
By default, Jinja also removes trailing newlines. To keep single |
| 269 |
trailing newlines, configure Jinja to `keep_trailing_newline`. |
| 270 |
|
| 271 |
.. admonition:: Note |
| 272 |
|
| 273 |
You must not add whitespace between the tag and the minus sign. |
| 274 |
|
| 275 |
**valid**:: |
| 276 |
|
| 277 |
{%- if foo -%}...{% endif %} |
| 278 |
|
| 279 |
**invalid**:: |
| 280 |
|
| 281 |
{% - if foo - %}...{% endif %} |
| 282 |
|
| 283 |
|
| 284 |
Escaping |
| 285 |
-------- |
| 286 |
|
| 287 |
It is sometimes desirable -- even necessary -- to have Jinja ignore parts |
| 288 |
it would otherwise handle as variables or blocks. For example, if, with |
| 289 |
the default syntax, you want to use ``{{`` as a raw string in a template and |
| 290 |
not start a variable, you have to use a trick. |
| 291 |
|
| 292 |
The easiest way to output a literal variable delimiter (``{{``) is by using a |
| 293 |
variable expression:: |
| 294 |
|
| 295 |
{{ '{{' }} |
| 296 |
|
| 297 |
For bigger sections, it makes sense to mark a block `raw`. For example, to |
| 298 |
include example Jinja syntax in a template, you can use this snippet:: |
| 299 |
|
| 300 |
{% raw %} |
| 301 |
<ul> |
| 302 |
{% for item in seq %} |
| 303 |
<li>{{ item }}</li> |
| 304 |
{% endfor %} |
| 305 |
</ul> |
| 306 |
{% endraw %} |
| 307 |
|
| 308 |
.. admonition:: Note |
| 309 |
|
| 310 |
Minus sign at the end of ``{% raw -%}`` tag cleans all the spaces and newlines |
| 311 |
preceding the first character of your raw data. |
| 312 |
|
| 313 |
|
| 314 |
.. _line-statements: |
| 315 |
|
| 316 |
Line Statements |
| 317 |
--------------- |
| 318 |
|
| 319 |
If line statements are enabled by the application, it's possible to mark a |
| 320 |
line as a statement. For example, if the line statement prefix is configured |
| 321 |
to ``#``, the following two examples are equivalent:: |
| 322 |
|
| 323 |
<ul> |
| 324 |
# for item in seq |
| 325 |
<li>{{ item }}</li> |
| 326 |
# endfor |
| 327 |
</ul> |
| 328 |
|
| 329 |
<ul> |
| 330 |
{% for item in seq %} |
| 331 |
<li>{{ item }}</li> |
| 332 |
{% endfor %} |
| 333 |
</ul> |
| 334 |
|
| 335 |
The line statement prefix can appear anywhere on the line as long as no text |
| 336 |
precedes it. For better readability, statements that start a block (such as |
| 337 |
`for`, `if`, `elif` etc.) may end with a colon:: |
| 338 |
|
| 339 |
# for item in seq: |
| 340 |
... |
| 341 |
# endfor |
| 342 |
|
| 343 |
|
| 344 |
.. admonition:: Note |
| 345 |
|
| 346 |
Line statements can span multiple lines if there are open parentheses, |
| 347 |
braces or brackets:: |
| 348 |
|
| 349 |
<ul> |
| 350 |
# for href, caption in [('index.html', 'Index'), |
| 351 |
('about.html', 'About')]: |
| 352 |
<li><a href="{{ href }}">{{ caption }}</a></li> |
| 353 |
# endfor |
| 354 |
</ul> |
| 355 |
|
| 356 |
Since Jinja 2.2, line-based comments are available as well. For example, if |
| 357 |
the line-comment prefix is configured to be ``##``, everything from ``##`` to |
| 358 |
the end of the line is ignored (excluding the newline sign):: |
| 359 |
|
| 360 |
# for item in seq: |
| 361 |
<li>{{ item }}</li> ## this comment is ignored |
| 362 |
# endfor |
| 363 |
|
| 364 |
|
| 365 |
.. _template-inheritance: |
| 366 |
|
| 367 |
Template Inheritance |
| 368 |
-------------------- |
| 369 |
|
| 370 |
The most powerful part of Jinja is template inheritance. Template inheritance |
| 371 |
allows you to build a base "skeleton" template that contains all the common |
| 372 |
elements of your site and defines **blocks** that child templates can override. |
| 373 |
|
| 374 |
Sounds complicated but is very basic. It's easiest to understand it by starting |
| 375 |
with an example. |
| 376 |
|
| 377 |
|
| 378 |
Base Template |
| 379 |
~~~~~~~~~~~~~ |
| 380 |
|
| 381 |
This template, which we'll call ``base.html``, defines a simple HTML skeleton |
| 382 |
document that you might use for a simple two-column page. It's the job of |
| 383 |
"child" templates to fill the empty blocks with content:: |
| 384 |
|
| 385 |
<!DOCTYPE html> |
| 386 |
<html lang="en"> |
| 387 |
<head> |
| 388 |
{% block head %} |
| 389 |
<link rel="stylesheet" href="style.css" /> |
| 390 |
<title>{% block title %}{% endblock %} - My Webpage</title> |
| 391 |
{% endblock %} |
| 392 |
</head> |
| 393 |
<body> |
| 394 |
<div id="content">{% block content %}{% endblock %}</div> |
| 395 |
<div id="footer"> |
| 396 |
{% block footer %} |
| 397 |
© Copyright 2008 by <a href="http://domain.invalid/">you</a>. |
| 398 |
{% endblock %} |
| 399 |
</div> |
| 400 |
</body> |
| 401 |
</html> |
| 402 |
|
| 403 |
In this example, the ``{% block %}`` tags define four blocks that child templates |
| 404 |
can fill in. All the `block` tag does is tell the template engine that a |
| 405 |
child template may override those placeholders in the template. |
| 406 |
|
| 407 |
``block`` tags can be inside other blocks such as ``if``, but they will |
| 408 |
always be executed regardless of if the ``if`` block is actually |
| 409 |
rendered. |
| 410 |
|
| 411 |
Child Template |
| 412 |
~~~~~~~~~~~~~~ |
| 413 |
|
| 414 |
A child template might look like this:: |
| 415 |
|
| 416 |
{% extends "base.html" %} |
| 417 |
{% block title %}Index{% endblock %} |
| 418 |
{% block head %} |
| 419 |
{{ super() }} |
| 420 |
<style type="text/css"> |
| 421 |
.important { color: #336699; } |
| 422 |
</style> |
| 423 |
{% endblock %} |
| 424 |
{% block content %} |
| 425 |
<h1>Index</h1> |
| 426 |
<p class="important"> |
| 427 |
Welcome to my awesome homepage. |
| 428 |
</p> |
| 429 |
{% endblock %} |
| 430 |
|
| 431 |
The ``{% extends %}`` tag is the key here. It tells the template engine that |
| 432 |
this template "extends" another template. When the template system evaluates |
| 433 |
this template, it first locates the parent. The extends tag should be the |
| 434 |
first tag in the template. Everything before it is printed out normally and |
| 435 |
may cause confusion. For details about this behavior and how to take |
| 436 |
advantage of it, see :ref:`null-default-fallback`. Also a block will always be |
| 437 |
filled in regardless of whether the surrounding condition is evaluated to be true |
| 438 |
or false. |
| 439 |
|
| 440 |
The filename of the template depends on the template loader. For example, the |
| 441 |
:class:`FileSystemLoader` allows you to access other templates by giving the |
| 442 |
filename. You can access templates in subdirectories with a slash:: |
| 443 |
|
| 444 |
{% extends "layout/default.html" %} |
| 445 |
|
| 446 |
But this behavior can depend on the application embedding Jinja. Note that |
| 447 |
since the child template doesn't define the ``footer`` block, the value from |
| 448 |
the parent template is used instead. |
| 449 |
|
| 450 |
You can't define multiple ``{% block %}`` tags with the same name in the |
| 451 |
same template. This limitation exists because a block tag works in "both" |
| 452 |
directions. That is, a block tag doesn't just provide a placeholder to fill |
| 453 |
- it also defines the content that fills the placeholder in the *parent*. |
| 454 |
If there were two similarly-named ``{% block %}`` tags in a template, |
| 455 |
that template's parent wouldn't know which one of the blocks' content to use. |
| 456 |
|
| 457 |
If you want to print a block multiple times, you can, however, use the special |
| 458 |
`self` variable and call the block with that name:: |
| 459 |
|
| 460 |
<title>{% block title %}{% endblock %}</title> |
| 461 |
<h1>{{ self.title() }}</h1> |
| 462 |
{% block body %}{% endblock %} |
| 463 |
|
| 464 |
|
| 465 |
Super Blocks |
| 466 |
~~~~~~~~~~~~ |
| 467 |
|
| 468 |
It's possible to render the contents of the parent block by calling ``super()``. |
| 469 |
This gives back the results of the parent block:: |
| 470 |
|
| 471 |
{% block sidebar %} |
| 472 |
<h3>Table Of Contents</h3> |
| 473 |
... |
| 474 |
{{ super() }} |
| 475 |
{% endblock %} |
| 476 |
|
| 477 |
|
| 478 |
Nesting extends |
| 479 |
~~~~~~~~~~~~~~~ |
| 480 |
|
| 481 |
In the case of multiple levels of ``{% extends %}``, |
| 482 |
``super`` references may be chained (as in ``super.super()``) |
| 483 |
to skip levels in the inheritance tree. |
| 484 |
|
| 485 |
For example:: |
| 486 |
|
| 487 |
# parent.tmpl |
| 488 |
body: {% block body %}Hi from parent.{% endblock %} |
| 489 |
|
| 490 |
# child.tmpl |
| 491 |
{% extends "parent.tmpl" %} |
| 492 |
{% block body %}Hi from child. {{ super() }}{% endblock %} |
| 493 |
|
| 494 |
# grandchild1.tmpl |
| 495 |
{% extends "child.tmpl" %} |
| 496 |
{% block body %}Hi from grandchild1.{% endblock %} |
| 497 |
|
| 498 |
# grandchild2.tmpl |
| 499 |
{% extends "child.tmpl" %} |
| 500 |
{% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %} |
| 501 |
|
| 502 |
|
| 503 |
Rendering ``child.tmpl`` will give |
| 504 |
``body: Hi from child. Hi from parent.`` |
| 505 |
|
| 506 |
Rendering ``grandchild1.tmpl`` will give |
| 507 |
``body: Hi from grandchild1.`` |
| 508 |
|
| 509 |
Rendering ``grandchild2.tmpl`` will give |
| 510 |
``body: Hi from grandchild2. Hi from parent.`` |
| 511 |
|
| 512 |
|
| 513 |
Named Block End-Tags |
| 514 |
~~~~~~~~~~~~~~~~~~~~ |
| 515 |
|
| 516 |
Jinja allows you to put the name of the block after the end tag for better |
| 517 |
readability:: |
| 518 |
|
| 519 |
{% block sidebar %} |
| 520 |
{% block inner_sidebar %} |
| 521 |
... |
| 522 |
{% endblock inner_sidebar %} |
| 523 |
{% endblock sidebar %} |
| 524 |
|
| 525 |
However, the name after the `endblock` word must match the block name. |
| 526 |
|
| 527 |
|
| 528 |
Block Nesting and Scope |
| 529 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 530 |
|
| 531 |
Blocks can be nested for more complex layouts. By default, a block may not |
| 532 |
access variables from outside the block (outer scopes):: |
| 533 |
|
| 534 |
{% for item in seq %} |
| 535 |
<li>{% block loop_item %}{{ item }}{% endblock %}</li> |
| 536 |
{% endfor %} |
| 537 |
|
| 538 |
This example would output empty ``<li>`` items because `item` is unavailable |
| 539 |
inside the block. The reason for this is that if the block is replaced by |
| 540 |
a child template, a variable would appear that was not defined in the block or |
| 541 |
passed to the context. |
| 542 |
|
| 543 |
Starting with Jinja 2.2, you can explicitly specify that variables are |
| 544 |
available in a block by setting the block to "scoped" by adding the `scoped` |
| 545 |
modifier to a block declaration:: |
| 546 |
|
| 547 |
{% for item in seq %} |
| 548 |
<li>{% block loop_item scoped %}{{ item }}{% endblock %}</li> |
| 549 |
{% endfor %} |
| 550 |
|
| 551 |
When overriding a block, the `scoped` modifier does not have to be provided. |
| 552 |
|
| 553 |
|
| 554 |
Required Blocks |
| 555 |
~~~~~~~~~~~~~~~ |
| 556 |
|
| 557 |
Blocks can be marked as ``required``. They must be overridden at some |
| 558 |
point, but not necessarily by the direct child template. Required blocks |
| 559 |
may only contain space and comments, and they cannot be rendered |
| 560 |
directly. |
| 561 |
|
| 562 |
.. code-block:: jinja |
| 563 |
:caption: ``page.txt`` |
| 564 |
|
| 565 |
{% block body required %}{% endblock %} |
| 566 |
|
| 567 |
.. code-block:: jinja |
| 568 |
:caption: ``issue.txt`` |
| 569 |
|
| 570 |
{% extends "page.txt" %} |
| 571 |
|
| 572 |
.. code-block:: jinja |
| 573 |
:caption: ``bug_report.txt`` |
| 574 |
|
| 575 |
{% extends "issue.txt" %} |
| 576 |
{% block body %}Provide steps to demonstrate the bug.{% endblock %} |
| 577 |
|
| 578 |
Rendering ``page.txt`` or ``issue.txt`` will raise |
| 579 |
``TemplateRuntimeError`` because they don't override the ``body`` block. |
| 580 |
Rendering ``bug_report.txt`` will succeed because it does override the |
| 581 |
block. |
| 582 |
|
| 583 |
When combined with ``scoped``, the ``required`` modifier must be placed |
| 584 |
*after* the scoped modifier. Here are some valid examples: |
| 585 |
|
| 586 |
.. code-block:: jinja |
| 587 |
|
| 588 |
{% block body scoped %}{% endblock %} |
| 589 |
{% block body required %}{% endblock %} |
| 590 |
{% block body scoped required %}{% endblock %} |
| 591 |
|
| 592 |
|
| 593 |
Template Objects |
| 594 |
~~~~~~~~~~~~~~~~ |
| 595 |
|
| 596 |
``extends``, ``include``, and ``import`` can take a template object |
| 597 |
instead of the name of a template to load. This could be useful in some |
| 598 |
advanced situations, since you can use Python code to load a template |
| 599 |
first and pass it in to ``render``. |
| 600 |
|
| 601 |
.. code-block:: python |
| 602 |
|
| 603 |
if debug_mode: |
| 604 |
layout = env.get_template("debug_layout.html") |
| 605 |
else: |
| 606 |
layout = env.get_template("layout.html") |
| 607 |
|
| 608 |
user_detail = env.get_template("user/detail.html") |
| 609 |
return user_detail.render(layout=layout) |
| 610 |
|
| 611 |
.. code-block:: jinja |
| 612 |
|
| 613 |
{% extends layout %} |
| 614 |
|
| 615 |
Note how ``extends`` is passed the variable with the template object |
| 616 |
that was passed to ``render``, instead of a string. |
| 617 |
|
| 618 |
|
| 619 |
HTML Escaping |
| 620 |
------------- |
| 621 |
|
| 622 |
When generating HTML from templates, there's always a risk that a variable will |
| 623 |
include characters that affect the resulting HTML. There are two approaches: |
| 624 |
|
| 625 |
a. manually escaping each variable; or |
| 626 |
b. automatically escaping everything by default. |
| 627 |
|
| 628 |
Jinja supports both. What is used depends on the application configuration. |
| 629 |
The default configuration is no automatic escaping; for various reasons: |
| 630 |
|
| 631 |
- Escaping everything except for safe values will also mean that Jinja is |
| 632 |
escaping variables known to not include HTML (e.g. numbers, booleans) |
| 633 |
which can be a huge performance hit. |
| 634 |
|
| 635 |
- The information about the safety of a variable is very fragile. It could |
| 636 |
happen that by coercing safe and unsafe values, the return value is |
| 637 |
double-escaped HTML. |
| 638 |
|
| 639 |
Working with Manual Escaping |
| 640 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 641 |
|
| 642 |
If manual escaping is enabled, it's **your** responsibility to escape |
| 643 |
variables if needed. What to escape? If you have a variable that *may* |
| 644 |
include any of the following chars (``>``, ``<``, ``&``, or ``"``) you |
| 645 |
**SHOULD** escape it unless the variable contains well-formed and trusted |
| 646 |
HTML. Escaping works by piping the variable through the ``|e`` filter:: |
| 647 |
|
| 648 |
{{ user.username|e }} |
| 649 |
|
| 650 |
Working with Automatic Escaping |
| 651 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 652 |
|
| 653 |
When automatic escaping is enabled, everything is escaped by default except |
| 654 |
for values explicitly marked as safe. Variables and expressions |
| 655 |
can be marked as safe either in: |
| 656 |
|
| 657 |
a. The context dictionary by the application with |
| 658 |
:class:`markupsafe.Markup` |
| 659 |
b. The template, with the ``|safe`` filter. |
| 660 |
|
| 661 |
If a string that you marked safe is passed through other Python code |
| 662 |
that doesn't understand that mark, it may get lost. Be aware of when |
| 663 |
your data is marked safe and how it is processed before arriving at the |
| 664 |
template. |
| 665 |
|
| 666 |
If a value has been escaped but is not marked safe, auto-escaping will |
| 667 |
still take place and result in double-escaped characters. If you know |
| 668 |
you have data that is already safe but not marked, be sure to wrap it in |
| 669 |
``Markup`` or use the ``|safe`` filter. |
| 670 |
|
| 671 |
Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template |
| 672 |
data that is marked as safe. |
| 673 |
|
| 674 |
String literals in templates with automatic escaping are considered |
| 675 |
unsafe because native Python strings are not safe. |
| 676 |
|
| 677 |
.. _list-of-control-structures: |
| 678 |
|
| 679 |
List of Control Structures |
| 680 |
-------------------------- |
| 681 |
|
| 682 |
A control structure refers to all those things that control the flow of a |
| 683 |
program - conditionals (i.e. if/elif/else), for-loops, as well as things like |
| 684 |
macros and blocks. With the default syntax, control structures appear inside |
| 685 |
``{% ... %}`` blocks. |
| 686 |
|
| 687 |
.. _for-loop: |
| 688 |
|
| 689 |
For |
| 690 |
~~~ |
| 691 |
|
| 692 |
Loop over each item in a sequence. For example, to display a list of users |
| 693 |
provided in a variable called `users`:: |
| 694 |
|
| 695 |
<h1>Members</h1> |
| 696 |
<ul> |
| 697 |
{% for user in users %} |
| 698 |
<li>{{ user.username|e }}</li> |
| 699 |
{% endfor %} |
| 700 |
</ul> |
| 701 |
|
| 702 |
As variables in templates retain their object properties, it is possible to |
| 703 |
iterate over containers like `dict`:: |
| 704 |
|
| 705 |
<dl> |
| 706 |
{% for key, value in my_dict.items() %} |
| 707 |
<dt>{{ key|e }}</dt> |
| 708 |
<dd>{{ value|e }}</dd> |
| 709 |
{% endfor %} |
| 710 |
</dl> |
| 711 |
|
| 712 |
Python dicts may not be in the order you want to display them in. If |
| 713 |
order matters, use the ``|dictsort`` filter. |
| 714 |
|
| 715 |
.. code-block:: jinja |
| 716 |
|
| 717 |
<dl> |
| 718 |
{% for key, value in my_dict | dictsort %} |
| 719 |
<dt>{{ key|e }}</dt> |
| 720 |
<dd>{{ value|e }}</dd> |
| 721 |
{% endfor %} |
| 722 |
</dl> |
| 723 |
|
| 724 |
Inside of a for-loop block, you can access some special variables: |
| 725 |
|
| 726 |
+-----------------------+---------------------------------------------------+ |
| 727 |
| Variable | Description | |
| 728 |
+=======================+===================================================+ |
| 729 |
| `loop.index` | The current iteration of the loop. (1 indexed) | |
| 730 |
+-----------------------+---------------------------------------------------+ |
| 731 |
| `loop.index0` | The current iteration of the loop. (0 indexed) | |
| 732 |
+-----------------------+---------------------------------------------------+ |
| 733 |
| `loop.revindex` | The number of iterations from the end of the loop | |
| 734 |
| | (1 indexed) | |
| 735 |
+-----------------------+---------------------------------------------------+ |
| 736 |
| `loop.revindex0` | The number of iterations from the end of the loop | |
| 737 |
| | (0 indexed) | |
| 738 |
+-----------------------+---------------------------------------------------+ |
| 739 |
| `loop.first` | True if first iteration. | |
| 740 |
+-----------------------+---------------------------------------------------+ |
| 741 |
| `loop.last` | True if last iteration. | |
| 742 |
+-----------------------+---------------------------------------------------+ |
| 743 |
| `loop.length` | The number of items in the sequence. | |
| 744 |
+-----------------------+---------------------------------------------------+ |
| 745 |
| `loop.cycle` | A helper function to cycle between a list of | |
| 746 |
| | sequences. See the explanation below. | |
| 747 |
+-----------------------+---------------------------------------------------+ |
| 748 |
| `loop.depth` | Indicates how deep in a recursive loop | |
| 749 |
| | the rendering currently is. Starts at level 1 | |
| 750 |
+-----------------------+---------------------------------------------------+ |
| 751 |
| `loop.depth0` | Indicates how deep in a recursive loop | |
| 752 |
| | the rendering currently is. Starts at level 0 | |
| 753 |
+-----------------------+---------------------------------------------------+ |
| 754 |
| `loop.previtem` | The item from the previous iteration of the loop. | |
| 755 |
| | Undefined during the first iteration. | |
| 756 |
+-----------------------+---------------------------------------------------+ |
| 757 |
| `loop.nextitem` | The item from the following iteration of the loop.| |
| 758 |
| | Undefined during the last iteration. | |
| 759 |
+-----------------------+---------------------------------------------------+ |
| 760 |
| `loop.changed(*val)` | True if previously called with a different value | |
| 761 |
| | (or not called at all). | |
| 762 |
+-----------------------+---------------------------------------------------+ |
| 763 |
|
| 764 |
Within a for-loop, it's possible to cycle among a list of strings/variables |
| 765 |
each time through the loop by using the special `loop.cycle` helper:: |
| 766 |
|
| 767 |
{% for row in rows %} |
| 768 |
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li> |
| 769 |
{% endfor %} |
| 770 |
|
| 771 |
Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound |
| 772 |
cycling. For more information, have a look at the :ref:`builtin-globals`. |
| 773 |
|
| 774 |
.. _loop-filtering: |
| 775 |
|
| 776 |
Unlike in Python, it's not possible to `break` or `continue` in a loop. You |
| 777 |
can, however, filter the sequence during iteration, which allows you to skip |
| 778 |
items. The following example skips all the users which are hidden:: |
| 779 |
|
| 780 |
{% for user in users if not user.hidden %} |
| 781 |
<li>{{ user.username|e }}</li> |
| 782 |
{% endfor %} |
| 783 |
|
| 784 |
The advantage is that the special `loop` variable will count correctly; thus |
| 785 |
not counting the users not iterated over. |
| 786 |
|
| 787 |
If no iteration took place because the sequence was empty or the filtering |
| 788 |
removed all the items from the sequence, you can render a default block |
| 789 |
by using `else`:: |
| 790 |
|
| 791 |
<ul> |
| 792 |
{% for user in users %} |
| 793 |
<li>{{ user.username|e }}</li> |
| 794 |
{% else %} |
| 795 |
<li><em>no users found</em></li> |
| 796 |
{% endfor %} |
| 797 |
</ul> |
| 798 |
|
| 799 |
Note that, in Python, `else` blocks are executed whenever the corresponding |
| 800 |
loop **did not** `break`. Since Jinja loops cannot `break` anyway, |
| 801 |
a slightly different behavior of the `else` keyword was chosen. |
| 802 |
|
| 803 |
It is also possible to use loops recursively. This is useful if you are |
| 804 |
dealing with recursive data such as sitemaps or RDFa. |
| 805 |
To use loops recursively, you basically have to add the `recursive` modifier |
| 806 |
to the loop definition and call the `loop` variable with the new iterable |
| 807 |
where you want to recurse. |
| 808 |
|
| 809 |
The following example implements a sitemap with recursive loops:: |
| 810 |
|
| 811 |
<ul class="sitemap"> |
| 812 |
{%- for item in sitemap recursive %} |
| 813 |
<li><a href="{{ item.href|e }}">{{ item.title }}</a> |
| 814 |
{%- if item.children -%} |
| 815 |
<ul class="submenu">{{ loop(item.children) }}</ul> |
| 816 |
{%- endif %}</li> |
| 817 |
{%- endfor %} |
| 818 |
</ul> |
| 819 |
|
| 820 |
The `loop` variable always refers to the closest (innermost) loop. If we |
| 821 |
have more than one level of loops, we can rebind the variable `loop` by |
| 822 |
writing `{% set outer_loop = loop %}` after the loop that we want to |
| 823 |
use recursively. Then, we can call it using `{{ outer_loop(...) }}` |
| 824 |
|
| 825 |
Please note that assignments in loops will be cleared at the end of the |
| 826 |
iteration and cannot outlive the loop scope. Older versions of Jinja had |
| 827 |
a bug where in some circumstances it appeared that assignments would work. |
| 828 |
This is not supported. See :ref:`assignments` for more information about |
| 829 |
how to deal with this. |
| 830 |
|
| 831 |
If all you want to do is check whether some value has changed since the |
| 832 |
last iteration or will change in the next iteration, you can use `previtem` |
| 833 |
and `nextitem`:: |
| 834 |
|
| 835 |
{% for value in values %} |
| 836 |
{% if loop.previtem is defined and value > loop.previtem %} |
| 837 |
The value just increased! |
| 838 |
{% endif %} |
| 839 |
{{ value }} |
| 840 |
{% if loop.nextitem is defined and loop.nextitem > value %} |
| 841 |
The value will increase even more! |
| 842 |
{% endif %} |
| 843 |
{% endfor %} |
| 844 |
|
| 845 |
If you only care whether the value changed at all, using `changed` is even |
| 846 |
easier:: |
| 847 |
|
| 848 |
{% for entry in entries %} |
| 849 |
{% if loop.changed(entry.category) %} |
| 850 |
<h2>{{ entry.category }}</h2> |
| 851 |
{% endif %} |
| 852 |
<p>{{ entry.message }}</p> |
| 853 |
{% endfor %} |
| 854 |
|
| 855 |
.. _if: |
| 856 |
|
| 857 |
If |
| 858 |
~~ |
| 859 |
|
| 860 |
The `if` statement in Jinja is comparable with the Python if statement. |
| 861 |
In the simplest form, you can use it to test if a variable is defined, not |
| 862 |
empty and not false:: |
| 863 |
|
| 864 |
{% if users %} |
| 865 |
<ul> |
| 866 |
{% for user in users %} |
| 867 |
<li>{{ user.username|e }}</li> |
| 868 |
{% endfor %} |
| 869 |
</ul> |
| 870 |
{% endif %} |
| 871 |
|
| 872 |
For multiple branches, `elif` and `else` can be used like in Python. You can |
| 873 |
use more complex :ref:`expressions` there, too:: |
| 874 |
|
| 875 |
{% if kenny.sick %} |
| 876 |
Kenny is sick. |
| 877 |
{% elif kenny.dead %} |
| 878 |
You killed Kenny! You bastard!!! |
| 879 |
{% else %} |
| 880 |
Kenny looks okay --- so far |
| 881 |
{% endif %} |
| 882 |
|
| 883 |
If can also be used as an :ref:`inline expression <if-expression>` and for |
| 884 |
:ref:`loop filtering <loop-filtering>`. |
| 885 |
|
| 886 |
.. _macros: |
| 887 |
|
| 888 |
Macros |
| 889 |
~~~~~~ |
| 890 |
|
| 891 |
Macros are comparable with functions in regular programming languages. They |
| 892 |
are useful to put often used idioms into reusable functions to not repeat |
| 893 |
yourself ("DRY"). |
| 894 |
|
| 895 |
Here's a small example of a macro that renders a form element:: |
| 896 |
|
| 897 |
{% macro input(name, value='', type='text', size=20) -%} |
| 898 |
<input type="{{ type }}" name="{{ name }}" value="{{ |
| 899 |
value|e }}" size="{{ size }}"> |
| 900 |
{%- endmacro %} |
| 901 |
|
| 902 |
The macro can then be called like a function in the namespace:: |
| 903 |
|
| 904 |
<p>{{ input('username') }}</p> |
| 905 |
<p>{{ input('password', type='password') }}</p> |
| 906 |
|
| 907 |
If the macro was defined in a different template, you have to |
| 908 |
:ref:`import <import>` it first. |
| 909 |
|
| 910 |
Inside macros, you have access to three special variables: |
| 911 |
|
| 912 |
`varargs` |
| 913 |
If more positional arguments are passed to the macro than accepted by the |
| 914 |
macro, they end up in the special `varargs` variable as a list of values. |
| 915 |
|
| 916 |
`kwargs` |
| 917 |
Like `varargs` but for keyword arguments. All unconsumed keyword |
| 918 |
arguments are stored in this special variable. |
| 919 |
|
| 920 |
`caller` |
| 921 |
If the macro was called from a :ref:`call<call>` tag, the caller is stored |
| 922 |
in this variable as a callable macro. |
| 923 |
|
| 924 |
Macros also expose some of their internal details. The following attributes |
| 925 |
are available on a macro object: |
| 926 |
|
| 927 |
`name` |
| 928 |
The name of the macro. ``{{ input.name }}`` will print ``input``. |
| 929 |
|
| 930 |
`arguments` |
| 931 |
A tuple of the names of arguments the macro accepts. |
| 932 |
|
| 933 |
`catch_kwargs` |
| 934 |
This is `true` if the macro accepts extra keyword arguments (i.e.: accesses |
| 935 |
the special `kwargs` variable). |
| 936 |
|
| 937 |
`catch_varargs` |
| 938 |
This is `true` if the macro accepts extra positional arguments (i.e.: |
| 939 |
accesses the special `varargs` variable). |
| 940 |
|
| 941 |
`caller` |
| 942 |
This is `true` if the macro accesses the special `caller` variable and may |
| 943 |
be called from a :ref:`call<call>` tag. |
| 944 |
|
| 945 |
If a macro name starts with an underscore, it's not exported and can't |
| 946 |
be imported. |
| 947 |
|
| 948 |
Due to how scopes work in Jinja, a macro in a child template does not |
| 949 |
override a macro in a parent template. The following will output |
| 950 |
"LAYOUT", not "CHILD". |
| 951 |
|
| 952 |
.. code-block:: jinja |
| 953 |
:caption: ``layout.txt`` |
| 954 |
|
| 955 |
{% macro foo() %}LAYOUT{% endmacro %} |
| 956 |
{% block body %}{% endblock %} |
| 957 |
|
| 958 |
.. code-block:: jinja |
| 959 |
:caption: ``child.txt`` |
| 960 |
|
| 961 |
{% extends 'layout.txt' %} |
| 962 |
{% macro foo() %}CHILD{% endmacro %} |
| 963 |
{% block body %}{{ foo() }}{% endblock %} |
| 964 |
|
| 965 |
|
| 966 |
.. _call: |
| 967 |
|
| 968 |
Call |
| 969 |
~~~~ |
| 970 |
|
| 971 |
In some cases it can be useful to pass a macro to another macro. For this |
| 972 |
purpose, you can use the special `call` block. The following example shows |
| 973 |
a macro that takes advantage of the call functionality and how it can be |
| 974 |
used:: |
| 975 |
|
| 976 |
{% macro render_dialog(title, class='dialog') -%} |
| 977 |
<div class="{{ class }}"> |
| 978 |
<h2>{{ title }}</h2> |
| 979 |
<div class="contents"> |
| 980 |
{{ caller() }} |
| 981 |
</div> |
| 982 |
</div> |
| 983 |
{%- endmacro %} |
| 984 |
|
| 985 |
{% call render_dialog('Hello World') %} |
| 986 |
This is a simple dialog rendered by using a macro and |
| 987 |
a call block. |
| 988 |
{% endcall %} |
| 989 |
|
| 990 |
It's also possible to pass arguments back to the call block. This makes it |
| 991 |
useful as a replacement for loops. Generally speaking, a call block works |
| 992 |
exactly like a macro without a name. |
| 993 |
|
| 994 |
Here's an example of how a call block can be used with arguments:: |
| 995 |
|
| 996 |
{% macro dump_users(users) -%} |
| 997 |
<ul> |
| 998 |
{%- for user in users %} |
| 999 |
<li><p>{{ user.username|e }}</p>{{ caller(user) }}</li> |
| 1000 |
{%- endfor %} |
| 1001 |
</ul> |
| 1002 |
{%- endmacro %} |
| 1003 |
|
| 1004 |
{% call(user) dump_users(list_of_user) %} |
| 1005 |
<dl> |
| 1006 |
<dt>Realname</dt> |
| 1007 |
<dd>{{ user.realname|e }}</dd> |
| 1008 |
<dt>Description</dt> |
| 1009 |
<dd>{{ user.description }}</dd> |
| 1010 |
</dl> |
| 1011 |
{% endcall %} |
| 1012 |
|
| 1013 |
|
| 1014 |
Filters |
| 1015 |
~~~~~~~ |
| 1016 |
|
| 1017 |
Filter sections allow you to apply regular Jinja filters on a block of |
| 1018 |
template data. Just wrap the code in the special `filter` section:: |
| 1019 |
|
| 1020 |
{% filter upper %} |
| 1021 |
This text becomes uppercase |
| 1022 |
{% endfilter %} |
| 1023 |
|
| 1024 |
Filters that accept arguments can be called like this:: |
| 1025 |
|
| 1026 |
{% filter center(100) %}Center this{% endfilter %} |
| 1027 |
|
| 1028 |
.. _assignments: |
| 1029 |
|
| 1030 |
Assignments |
| 1031 |
~~~~~~~~~~~ |
| 1032 |
|
| 1033 |
Inside code blocks, you can also assign values to variables. Assignments at |
| 1034 |
top level (outside of blocks, macros or loops) are exported from the template |
| 1035 |
like top level macros and can be imported by other templates. |
| 1036 |
|
| 1037 |
Assignments use the `set` tag and can have multiple targets:: |
| 1038 |
|
| 1039 |
{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %} |
| 1040 |
{% set key, value = call_something() %} |
| 1041 |
|
| 1042 |
.. admonition:: Scoping Behavior |
| 1043 |
|
| 1044 |
Please keep in mind that it is not possible to set variables inside a |
| 1045 |
block and have them show up outside of it. This also applies to |
| 1046 |
loops. The only exception to that rule are if statements which do not |
| 1047 |
introduce a scope. As a result the following template is not going |
| 1048 |
to do what you might expect:: |
| 1049 |
|
| 1050 |
{% set iterated = false %} |
| 1051 |
{% for item in seq %} |
| 1052 |
{{ item }} |
| 1053 |
{% set iterated = true %} |
| 1054 |
{% endfor %} |
| 1055 |
{% if not iterated %} did not iterate {% endif %} |
| 1056 |
|
| 1057 |
It is not possible with Jinja syntax to do this. Instead use |
| 1058 |
alternative constructs like the loop else block or the special `loop` |
| 1059 |
variable:: |
| 1060 |
|
| 1061 |
{% for item in seq %} |
| 1062 |
{{ item }} |
| 1063 |
{% else %} |
| 1064 |
did not iterate |
| 1065 |
{% endfor %} |
| 1066 |
|
| 1067 |
As of version 2.10 more complex use cases can be handled using namespace |
| 1068 |
objects which allow propagating of changes across scopes:: |
| 1069 |
|
| 1070 |
{% set ns = namespace(found=false) %} |
| 1071 |
{% for item in items %} |
| 1072 |
{% if item.check_something() %} |
| 1073 |
{% set ns.found = true %} |
| 1074 |
{% endif %} |
| 1075 |
* {{ item.title }} |
| 1076 |
{% endfor %} |
| 1077 |
Found item having something: {{ ns.found }} |
| 1078 |
|
| 1079 |
Note that the ``obj.attr`` notation in the `set` tag is only allowed for |
| 1080 |
namespace objects; attempting to assign an attribute on any other object |
| 1081 |
will raise an exception. |
| 1082 |
|
| 1083 |
.. versionadded:: 2.10 Added support for namespace objects |
| 1084 |
|
| 1085 |
|
| 1086 |
Block Assignments |
| 1087 |
~~~~~~~~~~~~~~~~~ |
| 1088 |
|
| 1089 |
It's possible to use `set` as a block to assign the content of the block to a |
| 1090 |
variable. This can be used to create multi-line strings, since Jinja doesn't |
| 1091 |
support Python's triple quotes (``"""``, ``'''``). |
| 1092 |
|
| 1093 |
Instead of using an equals sign and a value, you only write the variable name, |
| 1094 |
and everything until ``{% endset %}`` is captured. |
| 1095 |
|
| 1096 |
.. code-block:: jinja |
| 1097 |
|
| 1098 |
{% set navigation %} |
| 1099 |
<li><a href="/">Index</a> |
| 1100 |
<li><a href="/downloads">Downloads</a> |
| 1101 |
{% endset %} |
| 1102 |
|
| 1103 |
Filters applied to the variable name will be applied to the block's content. |
| 1104 |
|
| 1105 |
.. code-block:: jinja |
| 1106 |
|
| 1107 |
{% set reply | wordwrap %} |
| 1108 |
You wrote: |
| 1109 |
{{ message }} |
| 1110 |
{% endset %} |
| 1111 |
|
| 1112 |
.. versionadded:: 2.8 |
| 1113 |
|
| 1114 |
.. versionchanged:: 2.10 |
| 1115 |
|
| 1116 |
Block assignment supports filters. |
| 1117 |
|
| 1118 |
.. _extends: |
| 1119 |
|
| 1120 |
Extends |
| 1121 |
~~~~~~~ |
| 1122 |
|
| 1123 |
The `extends` tag can be used to extend one template from another. You can |
| 1124 |
have multiple `extends` tags in a file, but only one of them may be executed at |
| 1125 |
a time. |
| 1126 |
|
| 1127 |
See the section about :ref:`template-inheritance` above. |
| 1128 |
|
| 1129 |
|
| 1130 |
.. _blocks: |
| 1131 |
|
| 1132 |
Blocks |
| 1133 |
~~~~~~ |
| 1134 |
|
| 1135 |
Blocks are used for inheritance and act as both placeholders and replacements |
| 1136 |
at the same time. They are documented in detail in the |
| 1137 |
:ref:`template-inheritance` section. |
| 1138 |
|
| 1139 |
|
| 1140 |
Include |
| 1141 |
~~~~~~~ |
| 1142 |
|
| 1143 |
The ``include`` tag renders another template and outputs the result into |
| 1144 |
the current template. |
| 1145 |
|
| 1146 |
.. code-block:: jinja |
| 1147 |
|
| 1148 |
{% include 'header.html' %} |
| 1149 |
Body goes here. |
| 1150 |
{% include 'footer.html' %} |
| 1151 |
|
| 1152 |
The included template has access to context of the current template by |
| 1153 |
default. Use ``without context`` to use a separate context instead. |
| 1154 |
``with context`` is also valid, but is the default behavior. See |
| 1155 |
:ref:`import-visibility`. |
| 1156 |
|
| 1157 |
The included template can ``extend`` another template and override |
| 1158 |
blocks in that template. However, the current template cannot override |
| 1159 |
any blocks that the included template outputs. |
| 1160 |
|
| 1161 |
Use ``ignore missing`` to ignore the statement if the template does not |
| 1162 |
exist. It must be placed *before* a context visibility statement. |
| 1163 |
|
| 1164 |
.. code-block:: jinja |
| 1165 |
|
| 1166 |
{% include "sidebar.html" without context %} |
| 1167 |
{% include "sidebar.html" ignore missing %} |
| 1168 |
{% include "sidebar.html" ignore missing with context %} |
| 1169 |
{% include "sidebar.html" ignore missing without context %} |
| 1170 |
|
| 1171 |
If a list of templates is given, each will be tried in order until one |
| 1172 |
is not missing. This can be used with ``ignore missing`` to ignore if |
| 1173 |
none of the templates exist. |
| 1174 |
|
| 1175 |
.. code-block:: jinja |
| 1176 |
|
| 1177 |
{% include ['page_detailed.html', 'page.html'] %} |
| 1178 |
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} |
| 1179 |
|
| 1180 |
A variable, with either a template name or template object, can also be |
| 1181 |
passed to the statement. |
| 1182 |
|
| 1183 |
.. _import: |
| 1184 |
|
| 1185 |
Import |
| 1186 |
~~~~~~ |
| 1187 |
|
| 1188 |
Jinja supports putting often used code into macros. These macros can go into |
| 1189 |
different templates and get imported from there. This works similarly to the |
| 1190 |
import statements in Python. It's important to know that imports are cached |
| 1191 |
and imported templates don't have access to the current template variables, |
| 1192 |
just the globals by default. For more details about context behavior of |
| 1193 |
imports and includes, see :ref:`import-visibility`. |
| 1194 |
|
| 1195 |
There are two ways to import templates. You can import a complete template |
| 1196 |
into a variable or request specific macros / exported variables from it. |
| 1197 |
|
| 1198 |
Imagine we have a helper module that renders forms (called `forms.html`):: |
| 1199 |
|
| 1200 |
{% macro input(name, value='', type='text') -%} |
| 1201 |
<input type="{{ type }}" value="{{ value|e }}" name="{{ name }}"> |
| 1202 |
{%- endmacro %} |
| 1203 |
|
| 1204 |
{%- macro textarea(name, value='', rows=10, cols=40) -%} |
| 1205 |
<textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols |
| 1206 |
}}">{{ value|e }}</textarea> |
| 1207 |
{%- endmacro %} |
| 1208 |
|
| 1209 |
The easiest and most flexible way to access a template's variables |
| 1210 |
and macros is to import the whole template module into a variable. |
| 1211 |
That way, you can access the attributes:: |
| 1212 |
|
| 1213 |
{% import 'forms.html' as forms %} |
| 1214 |
<dl> |
| 1215 |
<dt>Username</dt> |
| 1216 |
<dd>{{ forms.input('username') }}</dd> |
| 1217 |
<dt>Password</dt> |
| 1218 |
<dd>{{ forms.input('password', type='password') }}</dd> |
| 1219 |
</dl> |
| 1220 |
<p>{{ forms.textarea('comment') }}</p> |
| 1221 |
|
| 1222 |
|
| 1223 |
Alternatively, you can import specific names from a template into the current |
| 1224 |
namespace:: |
| 1225 |
|
| 1226 |
{% from 'forms.html' import input as input_field, textarea %} |
| 1227 |
<dl> |
| 1228 |
<dt>Username</dt> |
| 1229 |
<dd>{{ input_field('username') }}</dd> |
| 1230 |
<dt>Password</dt> |
| 1231 |
<dd>{{ input_field('password', type='password') }}</dd> |
| 1232 |
</dl> |
| 1233 |
<p>{{ textarea('comment') }}</p> |
| 1234 |
|
| 1235 |
Macros and variables starting with one or more underscores are private and |
| 1236 |
cannot be imported. |
| 1237 |
|
| 1238 |
.. versionchanged:: 2.4 |
| 1239 |
If a template object was passed to the template context, you can |
| 1240 |
import from that object. |
| 1241 |
|
| 1242 |
|
| 1243 |
.. _import-visibility: |
| 1244 |
|
| 1245 |
Import Context Behavior |
| 1246 |
----------------------- |
| 1247 |
|
| 1248 |
By default, included templates are passed the current context and imported |
| 1249 |
templates are not. The reason for this is that imports, unlike includes, |
| 1250 |
are cached; as imports are often used just as a module that holds macros. |
| 1251 |
|
| 1252 |
This behavior can be changed explicitly: by adding `with context` |
| 1253 |
or `without context` to the import/include directive, the current context |
| 1254 |
can be passed to the template and caching is disabled automatically. |
| 1255 |
|
| 1256 |
Here are two examples:: |
| 1257 |
|
| 1258 |
{% from 'forms.html' import input with context %} |
| 1259 |
{% include 'header.html' without context %} |
| 1260 |
|
| 1261 |
.. admonition:: Note |
| 1262 |
|
| 1263 |
In Jinja 2.0, the context that was passed to the included template |
| 1264 |
did not include variables defined in the template. As a matter of |
| 1265 |
fact, this did not work:: |
| 1266 |
|
| 1267 |
{% for box in boxes %} |
| 1268 |
{% include "render_box.html" %} |
| 1269 |
{% endfor %} |
| 1270 |
|
| 1271 |
The included template ``render_box.html`` is *not* able to access |
| 1272 |
`box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able |
| 1273 |
to do so. |
| 1274 |
|
| 1275 |
|
| 1276 |
.. _expressions: |
| 1277 |
|
| 1278 |
Expressions |
| 1279 |
----------- |
| 1280 |
|
| 1281 |
Jinja allows basic expressions everywhere. These work very similarly to |
| 1282 |
regular Python; even if you're not working with Python |
| 1283 |
you should feel comfortable with it. |
| 1284 |
|
| 1285 |
Literals |
| 1286 |
~~~~~~~~ |
| 1287 |
|
| 1288 |
The simplest form of expressions are literals. Literals are representations |
| 1289 |
for Python objects such as strings and numbers. The following literals exist: |
| 1290 |
|
| 1291 |
``"Hello World"`` |
| 1292 |
Everything between two double or single quotes is a string. They are |
| 1293 |
useful whenever you need a string in the template (e.g. as |
| 1294 |
arguments to function calls and filters, or just to extend or include a |
| 1295 |
template). |
| 1296 |
|
| 1297 |
``42`` / ``123_456`` |
| 1298 |
Integers are whole numbers without a decimal part. The '_' character |
| 1299 |
can be used to separate groups for legibility. |
| 1300 |
|
| 1301 |
``42.23`` / ``42.1e2`` / ``123_456.789`` |
| 1302 |
Floating point numbers can be written using a '.' as a decimal mark. |
| 1303 |
They can also be written in scientific notation with an upper or |
| 1304 |
lower case 'e' to indicate the exponent part. The '_' character can |
| 1305 |
be used to separate groups for legibility, but cannot be used in the |
| 1306 |
exponent part. |
| 1307 |
|
| 1308 |
``['list', 'of', 'objects']`` |
| 1309 |
Everything between two brackets is a list. Lists are useful for storing |
| 1310 |
sequential data to be iterated over. For example, you can easily |
| 1311 |
create a list of links using lists and tuples for (and with) a for loop:: |
| 1312 |
|
| 1313 |
<ul> |
| 1314 |
{% for href, caption in [('index.html', 'Index'), ('about.html', 'About'), |
| 1315 |
('downloads.html', 'Downloads')] %} |
| 1316 |
<li><a href="{{ href }}">{{ caption }}</a></li> |
| 1317 |
{% endfor %} |
| 1318 |
</ul> |
| 1319 |
|
| 1320 |
``('tuple', 'of', 'values')`` |
| 1321 |
Tuples are like lists that cannot be modified ("immutable"). If a tuple |
| 1322 |
only has one item, it must be followed by a comma (``('1-tuple',)``). |
| 1323 |
Tuples are usually used to represent items of two or more elements. |
| 1324 |
See the list example above for more details. |
| 1325 |
|
| 1326 |
``{'dict': 'of', 'key': 'and', 'value': 'pairs'}`` |
| 1327 |
A dict in Python is a structure that combines keys and values. Keys must |
| 1328 |
be unique and always have exactly one value. Dicts are rarely used in |
| 1329 |
templates; they are useful in some rare cases such as the :func:`xmlattr` |
| 1330 |
filter. |
| 1331 |
|
| 1332 |
``true`` / ``false`` |
| 1333 |
``true`` is always true and ``false`` is always false. |
| 1334 |
|
| 1335 |
.. admonition:: Note |
| 1336 |
|
| 1337 |
The special constants `true`, `false`, and `none` are indeed lowercase. |
| 1338 |
Because that caused confusion in the past, (`True` used to expand |
| 1339 |
to an undefined variable that was considered false), |
| 1340 |
all three can now also be written in title case |
| 1341 |
(`True`, `False`, and `None`). |
| 1342 |
However, for consistency, (all Jinja identifiers are lowercase) |
| 1343 |
you should use the lowercase versions. |
| 1344 |
|
| 1345 |
Math |
| 1346 |
~~~~ |
| 1347 |
|
| 1348 |
Jinja allows you to calculate with values. This is rarely useful in templates |
| 1349 |
but exists for completeness' sake. The following operators are supported: |
| 1350 |
|
| 1351 |
``+`` |
| 1352 |
Adds two objects together. Usually the objects are numbers, but if both are |
| 1353 |
strings or lists, you can concatenate them this way. This, however, is not |
| 1354 |
the preferred way to concatenate strings! For string concatenation, have |
| 1355 |
a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``. |
| 1356 |
|
| 1357 |
``-`` |
| 1358 |
Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``. |
| 1359 |
|
| 1360 |
``/`` |
| 1361 |
Divide two numbers. The return value will be a floating point number. |
| 1362 |
``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. |
| 1363 |
|
| 1364 |
``//`` |
| 1365 |
Divide two numbers and return the truncated integer result. |
| 1366 |
``{{ 20 // 7 }}`` is ``2``. |
| 1367 |
|
| 1368 |
``%`` |
| 1369 |
Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``. |
| 1370 |
|
| 1371 |
``*`` |
| 1372 |
Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would |
| 1373 |
return ``4``. This can also be used to repeat a string multiple times. |
| 1374 |
``{{ '=' * 80 }}`` would print a bar of 80 equal signs. |
| 1375 |
|
| 1376 |
``**`` |
| 1377 |
Raise the left operand to the power of the right operand. |
| 1378 |
``{{ 2**3 }}`` would return ``8``. |
| 1379 |
|
| 1380 |
Unlike Python, chained pow is evaluated left to right. |
| 1381 |
``{{ 3**3**3 }}`` is evaluated as ``(3**3)**3`` in Jinja, but would |
| 1382 |
be evaluated as ``3**(3**3)`` in Python. Use parentheses in Jinja |
| 1383 |
to be explicit about what order you want. It is usually preferable |
| 1384 |
to do extended math in Python and pass the results to ``render`` |
| 1385 |
rather than doing it in the template. |
| 1386 |
|
| 1387 |
This behavior may be changed in the future to match Python, if it's |
| 1388 |
possible to introduce an upgrade path. |
| 1389 |
|
| 1390 |
|
| 1391 |
Comparisons |
| 1392 |
~~~~~~~~~~~ |
| 1393 |
|
| 1394 |
``==`` |
| 1395 |
Compares two objects for equality. |
| 1396 |
|
| 1397 |
``!=`` |
| 1398 |
Compares two objects for inequality. |
| 1399 |
|
| 1400 |
``>`` |
| 1401 |
``true`` if the left hand side is greater than the right hand side. |
| 1402 |
|
| 1403 |
``>=`` |
| 1404 |
``true`` if the left hand side is greater or equal to the right hand side. |
| 1405 |
|
| 1406 |
``<`` |
| 1407 |
``true`` if the left hand side is lower than the right hand side. |
| 1408 |
|
| 1409 |
``<=`` |
| 1410 |
``true`` if the left hand side is lower or equal to the right hand side. |
| 1411 |
|
| 1412 |
Logic |
| 1413 |
~~~~~ |
| 1414 |
|
| 1415 |
For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be |
| 1416 |
useful to combine multiple expressions. |
| 1417 |
|
| 1418 |
``and`` |
| 1419 |
For ``x and y``, if ``x`` is false, then the value is ``x``, else ``y``. In |
| 1420 |
a boolean context, this will be treated as ``True`` if both operands are |
| 1421 |
truthy. |
| 1422 |
|
| 1423 |
``or`` |
| 1424 |
For ``x or y``, if ``x`` is true, then the value is ``x``, else ``y``. In a |
| 1425 |
boolean context, this will be treated as ``True`` if at least one operand is |
| 1426 |
truthy. |
| 1427 |
|
| 1428 |
``not`` |
| 1429 |
For ``not x``, if ``x`` is false, then the value is ``True``, else |
| 1430 |
``False``. |
| 1431 |
|
| 1432 |
Prefer negating ``is`` and ``in`` using their infix notation: |
| 1433 |
``foo is not bar`` instead of ``not foo is bar``; ``foo not in bar`` instead |
| 1434 |
of ``not foo in bar``. All other expressions require prefix notation: |
| 1435 |
``not (foo and bar).`` |
| 1436 |
|
| 1437 |
``(expr)`` |
| 1438 |
Parentheses group an expression. This is used to change evaluation order, or |
| 1439 |
to make a long expression easier to read or less ambiguous. |
| 1440 |
|
| 1441 |
|
| 1442 |
Other Operators |
| 1443 |
~~~~~~~~~~~~~~~ |
| 1444 |
|
| 1445 |
The following operators are very useful but don't fit into any of the other |
| 1446 |
two categories: |
| 1447 |
|
| 1448 |
``in`` |
| 1449 |
Perform a sequence / mapping containment test. Returns true if the left |
| 1450 |
operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for |
| 1451 |
example, return true. |
| 1452 |
|
| 1453 |
``is`` |
| 1454 |
Performs a :ref:`test <tests>`. |
| 1455 |
|
| 1456 |
``|`` (pipe, vertical bar) |
| 1457 |
Applies a :ref:`filter <filters>`. |
| 1458 |
|
| 1459 |
``~`` (tilde) |
| 1460 |
Converts all operands into strings and concatenates them. |
| 1461 |
|
| 1462 |
``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set |
| 1463 |
to ``'John'``) ``Hello John!``. |
| 1464 |
|
| 1465 |
``()`` |
| 1466 |
Call a callable: ``{{ post.render() }}``. Inside of the parentheses you |
| 1467 |
can use positional arguments and keyword arguments like in Python: |
| 1468 |
|
| 1469 |
``{{ post.render(user, full=true) }}``. |
| 1470 |
|
| 1471 |
``.`` / ``[]`` |
| 1472 |
Get an attribute of an object. (See :ref:`variables`) |
| 1473 |
|
| 1474 |
|
| 1475 |
.. _if-expression: |
| 1476 |
|
| 1477 |
If Expression |
| 1478 |
~~~~~~~~~~~~~ |
| 1479 |
|
| 1480 |
It is also possible to use inline `if` expressions. These are useful in some |
| 1481 |
situations. For example, you can use this to extend from one template if a |
| 1482 |
variable is defined, otherwise from the default layout template:: |
| 1483 |
|
| 1484 |
{% extends layout_template if layout_template is defined else 'default.html' %} |
| 1485 |
|
| 1486 |
The general syntax is ``<do something> if <something is true> else <do |
| 1487 |
something else>``. |
| 1488 |
|
| 1489 |
The `else` part is optional. If not provided, the else block implicitly |
| 1490 |
evaluates into an :class:`Undefined` object (regardless of what ``undefined`` |
| 1491 |
in the environment is set to): |
| 1492 |
|
| 1493 |
.. code-block:: jinja |
| 1494 |
|
| 1495 |
{{ "[{}]".format(page.title) if page.title }} |
| 1496 |
|
| 1497 |
|
| 1498 |
.. _python-methods: |
| 1499 |
|
| 1500 |
Python Methods |
| 1501 |
~~~~~~~~~~~~~~ |
| 1502 |
|
| 1503 |
You can also use any of the methods defined on a variable's type. |
| 1504 |
The value returned from the method invocation is used as the value of the expression. |
| 1505 |
Here is an example that uses methods defined on strings (where ``page.title`` is a string): |
| 1506 |
|
| 1507 |
.. code-block:: text |
| 1508 |
|
| 1509 |
{{ page.title.capitalize() }} |
| 1510 |
|
| 1511 |
This works for methods on user-defined types. For example, if variable |
| 1512 |
``f`` of type ``Foo`` has a method ``bar`` defined on it, you can do the |
| 1513 |
following: |
| 1514 |
|
| 1515 |
.. code-block:: text |
| 1516 |
|
| 1517 |
{{ f.bar(value) }} |
| 1518 |
|
| 1519 |
Operator methods also work as expected. For example, ``%`` implements |
| 1520 |
printf-style for strings: |
| 1521 |
|
| 1522 |
.. code-block:: text |
| 1523 |
|
| 1524 |
{{ "Hello, %s!" % name }} |
| 1525 |
|
| 1526 |
Although you should prefer the ``.format`` method for that case (which |
| 1527 |
is a bit contrived in the context of rendering a template): |
| 1528 |
|
| 1529 |
.. code-block:: text |
| 1530 |
|
| 1531 |
{{ "Hello, {}!".format(name) }} |
| 1532 |
|
| 1533 |
|
| 1534 |
.. _builtin-filters: |
| 1535 |
|
| 1536 |
List of Builtin Filters |
| 1537 |
----------------------- |
| 1538 |
|
| 1539 |
.. py:currentmodule:: jinja-filters |
| 1540 |
|
| 1541 |
.. jinja:filters:: jinja2.defaults.DEFAULT_FILTERS |
| 1542 |
|
| 1543 |
|
| 1544 |
.. _builtin-tests: |
| 1545 |
|
| 1546 |
List of Builtin Tests |
| 1547 |
--------------------- |
| 1548 |
|
| 1549 |
.. py:currentmodule:: jinja-tests |
| 1550 |
|
| 1551 |
.. jinja:tests:: jinja2.defaults.DEFAULT_TESTS |
| 1552 |
|
| 1553 |
|
| 1554 |
.. _builtin-globals: |
| 1555 |
|
| 1556 |
List of Global Functions |
| 1557 |
------------------------ |
| 1558 |
|
| 1559 |
The following functions are available in the global scope by default: |
| 1560 |
|
| 1561 |
.. py:currentmodule:: jinja-globals |
| 1562 |
|
| 1563 |
.. function:: range([start,] stop[, step]) |
| 1564 |
|
| 1565 |
Return a list containing an arithmetic progression of integers. |
| 1566 |
``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``; |
| 1567 |
start (!) defaults to ``0``. |
| 1568 |
When step is given, it specifies the increment (or decrement). |
| 1569 |
For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``. |
| 1570 |
The end point is omitted! |
| 1571 |
These are exactly the valid indices for a list of 4 elements. |
| 1572 |
|
| 1573 |
This is useful to repeat a template block multiple times, e.g. |
| 1574 |
to fill a list. Imagine you have 7 users in the list but you want to |
| 1575 |
render three empty items to enforce a height with CSS:: |
| 1576 |
|
| 1577 |
<ul> |
| 1578 |
{% for user in users %} |
| 1579 |
<li>{{ user.username }}</li> |
| 1580 |
{% endfor %} |
| 1581 |
{% for number in range(10 - users|count) %} |
| 1582 |
<li class="empty"><span>...</span></li> |
| 1583 |
{% endfor %} |
| 1584 |
</ul> |
| 1585 |
|
| 1586 |
.. function:: lipsum(n=5, html=True, min=20, max=100) |
| 1587 |
|
| 1588 |
Generates some lorem ipsum for the template. By default, five paragraphs |
| 1589 |
of HTML are generated with each paragraph between 20 and 100 words. |
| 1590 |
If html is False, regular text is returned. This is useful to generate simple |
| 1591 |
contents for layout testing. |
| 1592 |
|
| 1593 |
.. function:: dict(\**items) |
| 1594 |
|
| 1595 |
A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same |
| 1596 |
as ``dict(foo='bar')``. |
| 1597 |
|
| 1598 |
.. class:: cycler(\*items) |
| 1599 |
|
| 1600 |
Cycle through values by yielding them one at a time, then restarting |
| 1601 |
once the end is reached. |
| 1602 |
|
| 1603 |
Similar to ``loop.cycle``, but can be used outside loops or across |
| 1604 |
multiple loops. For example, render a list of folders and files in a |
| 1605 |
list, alternating giving them "odd" and "even" classes. |
| 1606 |
|
| 1607 |
.. code-block:: html+jinja |
| 1608 |
|
| 1609 |
{% set row_class = cycler("odd", "even") %} |
| 1610 |
<ul class="browser"> |
| 1611 |
{% for folder in folders %} |
| 1612 |
<li class="folder {{ row_class.next() }}">{{ folder }} |
| 1613 |
{% endfor %} |
| 1614 |
{% for file in files %} |
| 1615 |
<li class="file {{ row_class.next() }}">{{ file }} |
| 1616 |
{% endfor %} |
| 1617 |
</ul> |
| 1618 |
|
| 1619 |
:param items: Each positional argument will be yielded in the order |
| 1620 |
given for each cycle. |
| 1621 |
|
| 1622 |
.. versionadded:: 2.1 |
| 1623 |
|
| 1624 |
.. property:: current |
| 1625 |
|
| 1626 |
Return the current item. Equivalent to the item that will be |
| 1627 |
returned next time :meth:`next` is called. |
| 1628 |
|
| 1629 |
.. method:: next() |
| 1630 |
|
| 1631 |
Return the current item, then advance :attr:`current` to the |
| 1632 |
next item. |
| 1633 |
|
| 1634 |
.. method:: reset() |
| 1635 |
|
| 1636 |
Resets the current item to the first item. |
| 1637 |
|
| 1638 |
.. class:: joiner(sep=', ') |
| 1639 |
|
| 1640 |
A tiny helper that can be used to "join" multiple sections. A joiner is |
| 1641 |
passed a string and will return that string every time it's called, except |
| 1642 |
the first time (in which case it returns an empty string). You can |
| 1643 |
use this to join things:: |
| 1644 |
|
| 1645 |
{% set pipe = joiner("|") %} |
| 1646 |
{% if categories %} {{ pipe() }} |
| 1647 |
Categories: {{ categories|join(", ") }} |
| 1648 |
{% endif %} |
| 1649 |
{% if author %} {{ pipe() }} |
| 1650 |
Author: {{ author() }} |
| 1651 |
{% endif %} |
| 1652 |
{% if can_edit %} {{ pipe() }} |
| 1653 |
<a href="?action=edit">Edit</a> |
| 1654 |
{% endif %} |
| 1655 |
|
| 1656 |
.. versionadded:: 2.1 |
| 1657 |
|
| 1658 |
.. class:: namespace(...) |
| 1659 |
|
| 1660 |
Creates a new container that allows attribute assignment using the |
| 1661 |
``{% set %}`` tag:: |
| 1662 |
|
| 1663 |
{% set ns = namespace() %} |
| 1664 |
{% set ns.foo = 'bar' %} |
| 1665 |
|
| 1666 |
The main purpose of this is to allow carrying a value from within a loop |
| 1667 |
body to an outer scope. Initial values can be provided as a dict, as |
| 1668 |
keyword arguments, or both (same behavior as Python's `dict` constructor):: |
| 1669 |
|
| 1670 |
{% set ns = namespace(found=false) %} |
| 1671 |
{% for item in items %} |
| 1672 |
{% if item.check_something() %} |
| 1673 |
{% set ns.found = true %} |
| 1674 |
{% endif %} |
| 1675 |
* {{ item.title }} |
| 1676 |
{% endfor %} |
| 1677 |
Found item having something: {{ ns.found }} |
| 1678 |
|
| 1679 |
.. versionadded:: 2.10 |
| 1680 |
|
| 1681 |
.. versionchanged:: 3.2 |
| 1682 |
Namespace attributes can be assigned to in multiple assignment. |
| 1683 |
|
| 1684 |
|
| 1685 |
Extensions |
| 1686 |
---------- |
| 1687 |
|
| 1688 |
.. py:currentmodule:: jinja2 |
| 1689 |
|
| 1690 |
The following sections cover the built-in Jinja extensions that may be |
| 1691 |
enabled by an application. An application could also provide further |
| 1692 |
extensions not covered by this documentation; in which case there should |
| 1693 |
be a separate document explaining said :ref:`extensions |
| 1694 |
<jinja-extensions>`. |
| 1695 |
|
| 1696 |
|
| 1697 |
.. _i18n-in-templates: |
| 1698 |
|
| 1699 |
i18n |
| 1700 |
~~~~ |
| 1701 |
|
| 1702 |
If the :ref:`i18n-extension` is enabled, it's possible to mark text in |
| 1703 |
the template as translatable. To mark a section as translatable, use a |
| 1704 |
``trans`` block: |
| 1705 |
|
| 1706 |
.. code-block:: jinja |
| 1707 |
|
| 1708 |
{% trans %}Hello, {{ user }}!{% endtrans %} |
| 1709 |
|
| 1710 |
Inside the block, no statements are allowed, only text and simple |
| 1711 |
variable tags. |
| 1712 |
|
| 1713 |
Variable tags can only be a name, not attribute access, filters, or |
| 1714 |
other expressions. To use an expression, bind it to a name in the |
| 1715 |
``trans`` tag for use in the block. |
| 1716 |
|
| 1717 |
.. code-block:: jinja |
| 1718 |
|
| 1719 |
{% trans user=user.username %}Hello, {{ user }}!{% endtrans %} |
| 1720 |
|
| 1721 |
To bind more than one expression, separate each with a comma (``,``). |
| 1722 |
|
| 1723 |
.. code-block:: jinja |
| 1724 |
|
| 1725 |
{% trans book_title=book.title, author=author.name %} |
| 1726 |
This is {{ book_title }} by {{ author }} |
| 1727 |
{% endtrans %} |
| 1728 |
|
| 1729 |
To pluralize, specify both the singular and plural forms separated by |
| 1730 |
the ``pluralize`` tag. |
| 1731 |
|
| 1732 |
.. code-block:: jinja |
| 1733 |
|
| 1734 |
{% trans count=list|length %} |
| 1735 |
There is {{ count }} {{ name }} object. |
| 1736 |
{% pluralize %} |
| 1737 |
There are {{ count }} {{ name }} objects. |
| 1738 |
{% endtrans %} |
| 1739 |
|
| 1740 |
By default, the first variable in a block is used to determine whether |
| 1741 |
to use singular or plural form. If that isn't correct, specify the |
| 1742 |
variable used for pluralizing as a parameter to ``pluralize``. |
| 1743 |
|
| 1744 |
.. code-block:: jinja |
| 1745 |
|
| 1746 |
{% trans ..., user_count=users|length %}... |
| 1747 |
{% pluralize user_count %}...{% endtrans %} |
| 1748 |
|
| 1749 |
When translating blocks of text, whitespace and linebreaks result in |
| 1750 |
hard to read and error-prone translation strings. To avoid this, a trans |
| 1751 |
block can be marked as trimmed, which will replace all linebreaks and |
| 1752 |
the whitespace surrounding them with a single space and remove leading |
| 1753 |
and trailing whitespace. |
| 1754 |
|
| 1755 |
.. code-block:: jinja |
| 1756 |
|
| 1757 |
{% trans trimmed book_title=book.title %} |
| 1758 |
This is {{ book_title }}. |
| 1759 |
You should read it! |
| 1760 |
{% endtrans %} |
| 1761 |
|
| 1762 |
This results in ``This is %(book_title)s. You should read it!`` in the |
| 1763 |
translation file. |
| 1764 |
|
| 1765 |
If trimming is enabled globally, the ``notrimmed`` modifier can be used |
| 1766 |
to disable it for a block. |
| 1767 |
|
| 1768 |
.. versionadded:: 2.10 |
| 1769 |
The ``trimmed`` and ``notrimmed`` modifiers have been added. |
| 1770 |
|
| 1771 |
If the translation depends on the context that the message appears in, |
| 1772 |
the ``pgettext`` and ``npgettext`` functions take a ``context`` string |
| 1773 |
as the first argument, which is used to select the appropriate |
| 1774 |
translation. To specify a context with the ``{% trans %}`` tag, provide |
| 1775 |
a string as the first token after ``trans``. |
| 1776 |
|
| 1777 |
.. code-block:: jinja |
| 1778 |
|
| 1779 |
{% trans "fruit" %}apple{% endtrans %} |
| 1780 |
{% trans "fruit" trimmed count -%} |
| 1781 |
1 apple |
| 1782 |
{%- pluralize -%} |
| 1783 |
{{ count }} apples |
| 1784 |
{%- endtrans %} |
| 1785 |
|
| 1786 |
.. versionadded:: 3.1 |
| 1787 |
A context can be passed to the ``trans`` tag to use ``pgettext`` and |
| 1788 |
``npgettext``. |
| 1789 |
|
| 1790 |
It's possible to translate strings in expressions with these functions: |
| 1791 |
|
| 1792 |
- ``_(message)``: Alias for ``gettext``. |
| 1793 |
- ``gettext(message)``: Translate a message. |
| 1794 |
- ``ngettext(singular, plural, n)``: Translate a singular or plural |
| 1795 |
message based on a count variable. |
| 1796 |
- ``pgettext(context, message)``: Like ``gettext()``, but picks the |
| 1797 |
translation based on the context string. |
| 1798 |
- ``npgettext(context, singular, plural, n)``: Like ``npgettext()``, |
| 1799 |
but picks the translation based on the context string. |
| 1800 |
|
| 1801 |
You can print a translated string like this: |
| 1802 |
|
| 1803 |
.. code-block:: jinja |
| 1804 |
|
| 1805 |
{{ _("Hello, World!") }} |
| 1806 |
|
| 1807 |
To use placeholders, use the ``format`` filter. |
| 1808 |
|
| 1809 |
.. code-block:: jinja |
| 1810 |
|
| 1811 |
{{ _("Hello, %(user)s!")|format(user=user.username) }} |
| 1812 |
|
| 1813 |
Always use keyword arguments to ``format``, as other languages may not |
| 1814 |
use the words in the same order. |
| 1815 |
|
| 1816 |
If :ref:`newstyle-gettext` calls are activated, using placeholders is |
| 1817 |
easier. Formatting is part of the ``gettext`` call instead of using the |
| 1818 |
``format`` filter. |
| 1819 |
|
| 1820 |
.. sourcecode:: jinja |
| 1821 |
|
| 1822 |
{{ gettext('Hello World!') }} |
| 1823 |
{{ gettext('Hello %(name)s!', name='World') }} |
| 1824 |
{{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} |
| 1825 |
|
| 1826 |
The ``ngettext`` function's format string automatically receives the |
| 1827 |
count as a ``num`` parameter in addition to the given parameters. |
| 1828 |
|
| 1829 |
|
| 1830 |
Expression Statement |
| 1831 |
~~~~~~~~~~~~~~~~~~~~ |
| 1832 |
|
| 1833 |
If the expression-statement extension is loaded, a tag called `do` is available |
| 1834 |
that works exactly like the regular variable expression (``{{ ... }}``); except |
| 1835 |
it doesn't print anything. This can be used to modify lists:: |
| 1836 |
|
| 1837 |
{% do navigation.append('a string') %} |
| 1838 |
|
| 1839 |
|
| 1840 |
Loop Controls |
| 1841 |
~~~~~~~~~~~~~ |
| 1842 |
|
| 1843 |
If the application enables the :ref:`loopcontrols-extension`, it's possible to |
| 1844 |
use `break` and `continue` in loops. When `break` is reached, the loop is |
| 1845 |
terminated; if `continue` is reached, the processing is stopped and continues |
| 1846 |
with the next iteration. |
| 1847 |
|
| 1848 |
Here's a loop that skips every second item:: |
| 1849 |
|
| 1850 |
{% for user in users %} |
| 1851 |
{%- if loop.index is even %}{% continue %}{% endif %} |
| 1852 |
... |
| 1853 |
{% endfor %} |
| 1854 |
|
| 1855 |
Likewise, a loop that stops processing after the 10th iteration:: |
| 1856 |
|
| 1857 |
{% for user in users %} |
| 1858 |
{%- if loop.index >= 10 %}{% break %}{% endif %} |
| 1859 |
{%- endfor %} |
| 1860 |
|
| 1861 |
Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0 |
| 1862 |
(See: :ref:`for-loop`). |
| 1863 |
|
| 1864 |
|
| 1865 |
Debug Statement |
| 1866 |
~~~~~~~~~~~~~~~ |
| 1867 |
|
| 1868 |
If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be |
| 1869 |
available to dump the current context as well as the available filters |
| 1870 |
and tests. This is useful to see what's available to use in the template |
| 1871 |
without setting up a debugger. |
| 1872 |
|
| 1873 |
.. code-block:: html+jinja |
| 1874 |
|
| 1875 |
<pre>{% debug %}</pre> |
| 1876 |
|
| 1877 |
.. code-block:: text |
| 1878 |
|
| 1879 |
{'context': {'cycler': <class 'jinja2.utils.Cycler'>, |
| 1880 |
..., |
| 1881 |
'namespace': <class 'jinja2.utils.Namespace'>}, |
| 1882 |
'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd', |
| 1883 |
..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'], |
| 1884 |
'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined', |
| 1885 |
..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']} |
| 1886 |
|
| 1887 |
|
| 1888 |
With Statement |
| 1889 |
~~~~~~~~~~~~~~ |
| 1890 |
|
| 1891 |
.. versionadded:: 2.3 |
| 1892 |
|
| 1893 |
The with statement makes it possible to create a new inner scope. |
| 1894 |
Variables set within this scope are not visible outside of the scope. |
| 1895 |
|
| 1896 |
With in a nutshell:: |
| 1897 |
|
| 1898 |
{% with %} |
| 1899 |
{% set foo = 42 %} |
| 1900 |
{{ foo }} foo is 42 here |
| 1901 |
{% endwith %} |
| 1902 |
foo is not visible here any longer |
| 1903 |
|
| 1904 |
Because it is common to set variables at the beginning of the scope, |
| 1905 |
you can do that within the `with` statement. The following two examples |
| 1906 |
are equivalent:: |
| 1907 |
|
| 1908 |
{% with foo = 42 %} |
| 1909 |
{{ foo }} |
| 1910 |
{% endwith %} |
| 1911 |
|
| 1912 |
{% with %} |
| 1913 |
{% set foo = 42 %} |
| 1914 |
{{ foo }} |
| 1915 |
{% endwith %} |
| 1916 |
|
| 1917 |
An important note on scoping here. In Jinja versions before 2.9 the |
| 1918 |
behavior of referencing one variable to another had some unintended |
| 1919 |
consequences. In particular one variable could refer to another defined |
| 1920 |
in the same with block's opening statement. This caused issues with the |
| 1921 |
cleaned up scoping behavior and has since been improved. In particular |
| 1922 |
in newer Jinja versions the following code always refers to the variable |
| 1923 |
`a` from outside the `with` block:: |
| 1924 |
|
| 1925 |
{% with a={}, b=a.attribute %}...{% endwith %} |
| 1926 |
|
| 1927 |
In earlier Jinja versions the `b` attribute would refer to the results of |
| 1928 |
the first attribute. If you depend on this behavior you can rewrite it to |
| 1929 |
use the ``set`` tag:: |
| 1930 |
|
| 1931 |
{% with a={} %} |
| 1932 |
{% set b = a.attribute %} |
| 1933 |
{% endwith %} |
| 1934 |
|
| 1935 |
.. admonition:: Extension |
| 1936 |
|
| 1937 |
In older versions of Jinja (before 2.9) it was required to enable this |
| 1938 |
feature with an extension. It's now enabled by default. |
| 1939 |
|
| 1940 |
.. _autoescape-overrides: |
| 1941 |
|
| 1942 |
Autoescape Overrides |
| 1943 |
-------------------- |
| 1944 |
|
| 1945 |
.. versionadded:: 2.4 |
| 1946 |
|
| 1947 |
If you want you can activate and deactivate the autoescaping from within |
| 1948 |
the templates. |
| 1949 |
|
| 1950 |
Example:: |
| 1951 |
|
| 1952 |
{% autoescape true %} |
| 1953 |
Autoescaping is active within this block |
| 1954 |
{% endautoescape %} |
| 1955 |
|
| 1956 |
{% autoescape false %} |
| 1957 |
Autoescaping is inactive within this block |
| 1958 |
{% endautoescape %} |
| 1959 |
|
| 1960 |
After an `endautoescape` the behavior is reverted to what it was before. |
| 1961 |
|
| 1962 |
.. admonition:: Extension |
| 1963 |
|
| 1964 |
In older versions of Jinja (before 2.9) it was required to enable this |
| 1965 |
feature with an extension. It's now enabled by default. |