templates.rst
This file
Path
docs/templates.rst
1,965 lines · 61.7 KiB
Last changed by
Merge branch 'stable'David Lordbefore adoption6aeab5d
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
Merge pull request #1398 from pallets/docs-filter-anchorDavid Lordbefore adoptionf04bde8
lines 1–3why, one step back1.. py:currentmodule:: jinja22.. highlight:: html+jinja3update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 4–57why, one step back4Template Designer Documentation5===============================67This document describes the syntax and semantics of the template engine and8will be most useful as reference to those creating Jinja templates. As the9template engine is very flexible, the configuration from the application can10be slightly different from the code presented here in terms of delimiters and11behavior of undefined values.121314Synopsis15--------1617A Jinja template is simply a text file. Jinja can generate any text-based18format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a19specific extension: ``.html``, ``.xml``, or any other extension is just fine.2021A template contains **variables** and/or **expressions**, which get replaced22with values when a template is *rendered*; and **tags**, which control the23logic of the template. The template syntax is heavily inspired by Django and24Python.2526Below is a minimal template that illustrates a few basics using the default27Jinja configuration. We will cover the details later in this document::2829 <!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>4041 <h1>My Webpage</h1>42 {{ a_variable }}4344 {# a comment #}45 </body>46 </html>4748The following example shows the default configuration settings. An application49developer can change the syntax configuration from ``{% foo %}`` to ``<% foo50%>``, or something similar.5152There are a few kinds of delimiters. The default Jinja delimiters are53configured as follows:5455* ``{% ... %}`` for :ref:`Statements <list-of-control-structures>`56* ``{{ ... }}`` for :ref:`Expressions` to print to the template output57* ``{# ... #}`` for :ref:`Comments` not included in the template outputMerge pull request #1367 from mvolfik/docs-fixDavid Lordbefore adoption4a941ca
lines 58–62why, one step back5859:ref:`Line Statements and Comments <line-statements>` are also possible,60though they don't have default prefix characters. To use them, set61``line_statement_prefix`` and ``line_comment_prefix`` when creating the62:class:`~jinja2.Environment`.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 63–204why, one step back636465Template File Extension66~~~~~~~~~~~~~~~~~~~~~~~6768As stated above, any file can be loaded as a template, regardless of69file extension. Adding a ``.jinja`` extension, like ``user.html.jinja``70may make it easier for some IDEs or editor plugins, but is not required.71Autoescaping, introduced later, can be applied based on file extension,72so you'll need to take the extra suffix into account in that case.7374Another good heuristic for identifying templates is that they are in a75``templates`` folder, regardless of extension. This is a common layout76for projects.777879.. _variables:8081Variables82---------8384Template variables are defined by the context dictionary passed to the85template.8687You can mess around with the variables in templates provided they are passed in88by the application. Variables may have attributes or elements on them you can89access too. What attributes a variable has depends heavily on the application90providing that variable.9192You can use a dot (``.``) to access attributes of a variable in addition93to the standard Python ``__getitem__`` "subscript" syntax (``[]``).9495The following lines do the same thing::9697 {{ foo.bar }}98 {{ foo['bar'] }}99100It's important to know that the outer double-curly braces are *not* part of the101variable, but the print statement. If you access variables inside tags don't102put the braces around them.103104If a variable or attribute does not exist, you will get back an undefined105value. What you can do with that kind of value depends on the application106configuration: the default behavior is to evaluate to an empty string if107printed or iterated over, and to fail for every other operation.108109.. _notes-on-subscriptions:110111.. admonition:: Implementation112113 For the sake of convenience, ``foo.bar`` in Jinja does the following114 things on the Python layer:115116 - 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.121122 ``foo['bar']`` works mostly the same with a small difference in sequence:123124 - 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.129130 This is important if an object has an item and attribute with the same131 name. Additionally, the :func:`attr` filter only looks up attributes.132133.. _filters:134135Filters136-------137138Variables can be modified by **filters**. Filters are separated from the139variable by a pipe symbol (``|``) and may have optional arguments in140parentheses. Multiple filters can be chained. The output of one filter is141applied to the next.142143For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from144variable `name` and title-case the output (``title(striptags(name))``).145146Filters that accept arguments have parentheses around the arguments, just like147a function call. For example: ``{{ listx|join(', ') }}`` will join a list with148commas (``str.join(', ', listx)``).149150The :ref:`builtin-filters` below describes all the builtin filters.151152.. _tests:153154Tests155-----156157Beside filters, there are also so-called "tests" available. Tests can be used158to test a variable against a common expression. To test a variable or159expression, you add `is` plus the name of the test after the variable. For160example, to find out if a variable is defined, you can do ``name is defined``,161which will then return true or false depending on whether `name` is defined162in the current template context.163164Tests can accept arguments, too. If the test only takes one argument, you can165leave out the parentheses. For example, the following two166expressions do the same thing::167168 {% if loop.index is divisibleby 3 %}169 {% if loop.index is divisibleby(3) %}170171The :ref:`builtin-tests` below describes all the builtin tests.172173174.. _comments:175176Comments177--------178179To comment-out part of a line in a template, use the comment syntax which is180by default set to ``{# ... #}``. This is useful to comment out parts of the181template for debugging or to add information for other template designers or182yourself::183184 {# note: commented-out template because we no longer use this185 {% for user in users %}186 ...187 {% endfor %}188 #}189190191Whitespace Control192------------------193194In the default configuration:195196* a single trailing newline is stripped if present197* other whitespace (spaces, tabs, newlines etc.) is returned unchanged198199If an application configures Jinja to `trim_blocks`, the first newline after a200template tag is removed automatically (like in PHP). The `lstrip_blocks`201option can also be set to strip tabs and spaces from the beginning of a202line to the start of a block. (Nothing will be stripped if there are203other characters before the start of the block.)204Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 205–207why, one step back205With both ``trim_blocks`` and ``lstrip_blocks`` disabled (the default), block206tags on their own lines will be removed, but a blank line will remain and the207spaces in the content will be preserved. For example, this template:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 208why, one step back208Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 209–210why, one step back209.. code-block:: jinja210update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 211–216why, one step back211 <div>212 {% if True %}213 yay214 {% endif %}215 </div>216Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 217–218why, one step back217With both ``trim_blocks`` and ``lstrip_blocks`` disabled, the template is218rendered with blank lines inside the div:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 219why, one step back219Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 220–221why, one step back220.. code-block:: text221update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 222–227why, one step back222 <div>223224 yay225226 </div>227Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 228–229why, one step back228With both ``trim_blocks`` and ``lstrip_blocks`` enabled, the template block229lines are completely removed:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 230why, one step back230Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 231–232why, one step back231.. code-block:: text232update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 233–435why, one step back233 <div>234 yay235 </div>236237You can manually disable the `lstrip_blocks` behavior by putting a238plus sign (``+``) at the start of a block::239240 <div>241 {%+ if something %}yay{% endif %}242 </div>243244Similarly, you can manually disable the ``trim_blocks`` behavior by245putting a plus sign (``+``) at the end of a block::246247 <div>248 {% if something +%}249 yay250 {% endif %}251 </div>252253You can also strip whitespace in templates by hand. If you add a minus254sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a255comment, or a variable expression, the whitespaces before or after256that block will be removed::257258 {% for item in seq -%}259 {{ item }}260 {%- endfor %}261262This will yield all elements without whitespace between them. If `seq` was263a list of numbers from ``1`` to ``9``, the output would be ``123456789``.264265If :ref:`line-statements` are enabled, they strip leading whitespace266automatically up to the beginning of the line.267268By default, Jinja also removes trailing newlines. To keep single269trailing newlines, configure Jinja to `keep_trailing_newline`.270271.. admonition:: Note272273 You must not add whitespace between the tag and the minus sign.274275 **valid**::276277 {%- if foo -%}...{% endif %}278279 **invalid**::280281 {% - if foo - %}...{% endif %}282283284Escaping285--------286287It is sometimes desirable -- even necessary -- to have Jinja ignore parts288it would otherwise handle as variables or blocks. For example, if, with289the default syntax, you want to use ``{{`` as a raw string in a template and290not start a variable, you have to use a trick.291292The easiest way to output a literal variable delimiter (``{{``) is by using a293variable expression::294295 {{ '{{' }}296297For bigger sections, it makes sense to mark a block `raw`. For example, to298include example Jinja syntax in a template, you can use this snippet::299300 {% raw %}301 <ul>302 {% for item in seq %}303 <li>{{ item }}</li>304 {% endfor %}305 </ul>306 {% endraw %}307308.. admonition:: Note309310 Minus sign at the end of ``{% raw -%}`` tag cleans all the spaces and newlines311 preceding the first character of your raw data.312313314.. _line-statements:315316Line Statements317---------------318319If line statements are enabled by the application, it's possible to mark a320line as a statement. For example, if the line statement prefix is configured321to ``#``, the following two examples are equivalent::322323 <ul>324 # for item in seq325 <li>{{ item }}</li>326 # endfor327 </ul>328329 <ul>330 {% for item in seq %}331 <li>{{ item }}</li>332 {% endfor %}333 </ul>334335The line statement prefix can appear anywhere on the line as long as no text336precedes it. For better readability, statements that start a block (such as337`for`, `if`, `elif` etc.) may end with a colon::338339 # for item in seq:340 ...341 # endfor342343344.. admonition:: Note345346 Line statements can span multiple lines if there are open parentheses,347 braces or brackets::348349 <ul>350 # for href, caption in [('index.html', 'Index'),351 ('about.html', 'About')]:352 <li><a href="{{ href }}">{{ caption }}</a></li>353 # endfor354 </ul>355356Since Jinja 2.2, line-based comments are available as well. For example, if357the line-comment prefix is configured to be ``##``, everything from ``##`` to358the end of the line is ignored (excluding the newline sign)::359360 # for item in seq:361 <li>{{ item }}</li> ## this comment is ignored362 # endfor363364365.. _template-inheritance:366367Template Inheritance368--------------------369370The most powerful part of Jinja is template inheritance. Template inheritance371allows you to build a base "skeleton" template that contains all the common372elements of your site and defines **blocks** that child templates can override.373374Sounds complicated but is very basic. It's easiest to understand it by starting375with an example.376377378Base Template379~~~~~~~~~~~~~380381This template, which we'll call ``base.html``, defines a simple HTML skeleton382document that you might use for a simple two-column page. It's the job of383"child" templates to fill the empty blocks with content::384385 <!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>402403In this example, the ``{% block %}`` tags define four blocks that child templates404can fill in. All the `block` tag does is tell the template engine that a405child template may override those placeholders in the template.406407``block`` tags can be inside other blocks such as ``if``, but they will408always be executed regardless of if the ``if`` block is actually409rendered.410411Child Template412~~~~~~~~~~~~~~413414A child template might look like this::415416 {% 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 %}430431The ``{% extends %}`` tag is the key here. It tells the template engine that432this template "extends" another template. When the template system evaluates433this template, it first locates the parent. The extends tag should be the434first tag in the template. Everything before it is printed out normally and435may cause confusion. For details about this behavior and how to takeMerge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3
line 436why, one step back436advantage of it, see :ref:`null-default-fallback`. Also a block will always beupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 437–530why, one step back437filled in regardless of whether the surrounding condition is evaluated to be true438or false.439440The filename of the template depends on the template loader. For example, the441:class:`FileSystemLoader` allows you to access other templates by giving the442filename. You can access templates in subdirectories with a slash::443444 {% extends "layout/default.html" %}445446But this behavior can depend on the application embedding Jinja. Note that447since the child template doesn't define the ``footer`` block, the value from448the parent template is used instead.449450You can't define multiple ``{% block %}`` tags with the same name in the451same template. This limitation exists because a block tag works in "both"452directions. That is, a block tag doesn't just provide a placeholder to fill453- it also defines the content that fills the placeholder in the *parent*.454If there were two similarly-named ``{% block %}`` tags in a template,455that template's parent wouldn't know which one of the blocks' content to use.456457If you want to print a block multiple times, you can, however, use the special458`self` variable and call the block with that name::459460 <title>{% block title %}{% endblock %}</title>461 <h1>{{ self.title() }}</h1>462 {% block body %}{% endblock %}463464465Super Blocks466~~~~~~~~~~~~467468It's possible to render the contents of the parent block by calling ``super()``.469This gives back the results of the parent block::470471 {% block sidebar %}472 <h3>Table Of Contents</h3>473 ...474 {{ super() }}475 {% endblock %}476477478Nesting extends479~~~~~~~~~~~~~~~480481In the case of multiple levels of ``{% extends %}``,482``super`` references may be chained (as in ``super.super()``)483to skip levels in the inheritance tree.484485For example::486487 # parent.tmpl488 body: {% block body %}Hi from parent.{% endblock %}489490 # child.tmpl491 {% extends "parent.tmpl" %}492 {% block body %}Hi from child. {{ super() }}{% endblock %}493494 # grandchild1.tmpl495 {% extends "child.tmpl" %}496 {% block body %}Hi from grandchild1.{% endblock %}497498 # grandchild2.tmpl499 {% extends "child.tmpl" %}500 {% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}501502503Rendering ``child.tmpl`` will give504``body: Hi from child. Hi from parent.``505506Rendering ``grandchild1.tmpl`` will give507``body: Hi from grandchild1.``508509Rendering ``grandchild2.tmpl`` will give510``body: Hi from grandchild2. Hi from parent.``511512513Named Block End-Tags514~~~~~~~~~~~~~~~~~~~~515516Jinja allows you to put the name of the block after the end tag for better517readability::518519 {% block sidebar %}520 {% block inner_sidebar %}521 ...522 {% endblock inner_sidebar %}523 {% endblock sidebar %}524525However, the name after the `endblock` word must match the block name.526527528Block Nesting and Scope529~~~~~~~~~~~~~~~~~~~~~~~530Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 531–532why, one step back531Blocks can be nested for more complex layouts. By default, a block may not532access variables from outside the block (outer scopes)::update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 533–595why, one step back533534 {% for item in seq %}535 <li>{% block loop_item %}{{ item }}{% endblock %}</li>536 {% endfor %}537538This example would output empty ``<li>`` items because `item` is unavailable539inside the block. The reason for this is that if the block is replaced by540a child template, a variable would appear that was not defined in the block or541passed to the context.542543Starting with Jinja 2.2, you can explicitly specify that variables are544available in a block by setting the block to "scoped" by adding the `scoped`545modifier to a block declaration::546547 {% for item in seq %}548 <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>549 {% endfor %}550551When overriding a block, the `scoped` modifier does not have to be provided.552553554Required Blocks555~~~~~~~~~~~~~~~556557Blocks can be marked as ``required``. They must be overridden at some558point, but not necessarily by the direct child template. Required blocks559may only contain space and comments, and they cannot be rendered560directly.561562.. code-block:: jinja563 :caption: ``page.txt``564565 {% block body required %}{% endblock %}566567.. code-block:: jinja568 :caption: ``issue.txt``569570 {% extends "page.txt" %}571572.. code-block:: jinja573 :caption: ``bug_report.txt``574575 {% extends "issue.txt" %}576 {% block body %}Provide steps to demonstrate the bug.{% endblock %}577578Rendering ``page.txt`` or ``issue.txt`` will raise579``TemplateRuntimeError`` because they don't override the ``body`` block.580Rendering ``bug_report.txt`` will succeed because it does override the581block.582583When combined with ``scoped``, the ``required`` modifier must be placed584*after* the scoped modifier. Here are some valid examples:585586.. code-block:: jinja587588 {% block body scoped %}{% endblock %}589 {% block body required %}{% endblock %}590 {% block body scoped required %}{% endblock %}591592593Template Objects594~~~~~~~~~~~~~~~~595Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 596–599why, one step back596``extends``, ``include``, and ``import`` can take a template object597instead of the name of a template to load. This could be useful in some598advanced situations, since you can use Python code to load a template599first and pass it in to ``render``.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 600why, one step back600Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 601why, one step back601.. code-block:: pythonupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 602why, one step back602Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 603–606why, one step back603 if debug_mode:604 layout = env.get_template("debug_layout.html")605 else:606 layout = env.get_template("layout.html")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 607why, one step back607Merge branch '3.1.x'David Lordbefore adoption94fd2d9
lines 608–609why, one step back608 user_detail = env.get_template("user/detail.html")609 return user_detail.render(layout=layout)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 610why, one step back610Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 611why, one step back611.. code-block:: jinjaupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 612why, one step back612Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 613–618why, one step back613 {% extends layout %}614615Note how ``extends`` is passed the variable with the template object616that was passed to ``render``, instead of a string.617618update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 619–711why, one step back619HTML Escaping620-------------621622When generating HTML from templates, there's always a risk that a variable will623include characters that affect the resulting HTML. There are two approaches:624625a. manually escaping each variable; or626b. automatically escaping everything by default.627628Jinja supports both. What is used depends on the application configuration.629The default configuration is no automatic escaping; for various reasons:630631- Escaping everything except for safe values will also mean that Jinja is632 escaping variables known to not include HTML (e.g. numbers, booleans)633 which can be a huge performance hit.634635- The information about the safety of a variable is very fragile. It could636 happen that by coercing safe and unsafe values, the return value is637 double-escaped HTML.638639Working with Manual Escaping640~~~~~~~~~~~~~~~~~~~~~~~~~~~~641642If manual escaping is enabled, it's **your** responsibility to escape643variables if needed. What to escape? If you have a variable that *may*644include any of the following chars (``>``, ``<``, ``&``, or ``"``) you645**SHOULD** escape it unless the variable contains well-formed and trusted646HTML. Escaping works by piping the variable through the ``|e`` filter::647648 {{ user.username|e }}649650Working with Automatic Escaping651~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~652653When automatic escaping is enabled, everything is escaped by default except654for values explicitly marked as safe. Variables and expressions655can be marked as safe either in:656657a. The context dictionary by the application with658 :class:`markupsafe.Markup`659b. The template, with the ``|safe`` filter.660661If a string that you marked safe is passed through other Python code662that doesn't understand that mark, it may get lost. Be aware of when663your data is marked safe and how it is processed before arriving at the664template.665666If a value has been escaped but is not marked safe, auto-escaping will667still take place and result in double-escaped characters. If you know668you have data that is already safe but not marked, be sure to wrap it in669``Markup`` or use the ``|safe`` filter.670671Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template672data that is marked as safe.673674String literals in templates with automatic escaping are considered675unsafe because native Python strings are not safe.676677.. _list-of-control-structures:678679List of Control Structures680--------------------------681682A control structure refers to all those things that control the flow of a683program - conditionals (i.e. if/elif/else), for-loops, as well as things like684macros and blocks. With the default syntax, control structures appear inside685``{% ... %}`` blocks.686687.. _for-loop:688689For690~~~691692Loop over each item in a sequence. For example, to display a list of users693provided in a variable called `users`::694695 <h1>Members</h1>696 <ul>697 {% for user in users %}698 <li>{{ user.username|e }}</li>699 {% endfor %}700 </ul>701702As variables in templates retain their object properties, it is possible to703iterate over containers like `dict`::704705 <dl>706 {% for key, value in my_dict.items() %}707 <dt>{{ key|e }}</dt>708 <dd>{{ value|e }}</dd>709 {% endfor %}710 </dl>711Merge pull request #1236 from sixtyfathoms/fix/issue-1184David Lordbefore adoptione45eabc
lines 712–722why, one step back712Python dicts may not be in the order you want to display them in. If713order matters, use the ``|dictsort`` filter.714715.. code-block:: jinja716717 <dl>718 {% for key, value in my_dict | dictsort %}719 <dt>{{ key|e }}</dt>720 <dd>{{ value|e }}</dd>721 {% endfor %}722 </dl>update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 723–947why, one step back723724Inside of a for-loop block, you can access some special variables:725726+-----------------------+---------------------------------------------------+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+-----------------------+---------------------------------------------------+763764Within a for-loop, it's possible to cycle among a list of strings/variables765each time through the loop by using the special `loop.cycle` helper::766767 {% for row in rows %}768 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>769 {% endfor %}770771Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound772cycling. For more information, have a look at the :ref:`builtin-globals`.773774.. _loop-filtering:775776Unlike in Python, it's not possible to `break` or `continue` in a loop. You777can, however, filter the sequence during iteration, which allows you to skip778items. The following example skips all the users which are hidden::779780 {% for user in users if not user.hidden %}781 <li>{{ user.username|e }}</li>782 {% endfor %}783784The advantage is that the special `loop` variable will count correctly; thus785not counting the users not iterated over.786787If no iteration took place because the sequence was empty or the filtering788removed all the items from the sequence, you can render a default block789by using `else`::790791 <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>798799Note that, in Python, `else` blocks are executed whenever the corresponding800loop **did not** `break`. Since Jinja loops cannot `break` anyway,801a slightly different behavior of the `else` keyword was chosen.802803It is also possible to use loops recursively. This is useful if you are804dealing with recursive data such as sitemaps or RDFa.805To use loops recursively, you basically have to add the `recursive` modifier806to the loop definition and call the `loop` variable with the new iterable807where you want to recurse.808809The following example implements a sitemap with recursive loops::810811 <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>819820The `loop` variable always refers to the closest (innermost) loop. If we821have more than one level of loops, we can rebind the variable `loop` by822writing `{% set outer_loop = loop %}` after the loop that we want to823use recursively. Then, we can call it using `{{ outer_loop(...) }}`824825Please note that assignments in loops will be cleared at the end of the826iteration and cannot outlive the loop scope. Older versions of Jinja had827a bug where in some circumstances it appeared that assignments would work.828This is not supported. See :ref:`assignments` for more information about829how to deal with this.830831If all you want to do is check whether some value has changed since the832last iteration or will change in the next iteration, you can use `previtem`833and `nextitem`::834835 {% 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 %}844845If you only care whether the value changed at all, using `changed` is even846easier::847848 {% for entry in entries %}849 {% if loop.changed(entry.category) %}850 <h2>{{ entry.category }}</h2>851 {% endif %}852 <p>{{ entry.message }}</p>853 {% endfor %}854855.. _if:856857If858~~859860The `if` statement in Jinja is comparable with the Python if statement.861In the simplest form, you can use it to test if a variable is defined, not862empty and not false::863864 {% if users %}865 <ul>866 {% for user in users %}867 <li>{{ user.username|e }}</li>868 {% endfor %}869 </ul>870 {% endif %}871872For multiple branches, `elif` and `else` can be used like in Python. You can873use more complex :ref:`expressions` there, too::874875 {% if kenny.sick %}876 Kenny is sick.877 {% elif kenny.dead %}878 You killed Kenny! You bastard!!!879 {% else %}880 Kenny looks okay --- so far881 {% endif %}882883If can also be used as an :ref:`inline expression <if-expression>` and for884:ref:`loop filtering <loop-filtering>`.885886.. _macros:887888Macros889~~~~~~890891Macros are comparable with functions in regular programming languages. They892are useful to put often used idioms into reusable functions to not repeat893yourself ("DRY").894895Here's a small example of a macro that renders a form element::896897 {% macro input(name, value='', type='text', size=20) -%}898 <input type="{{ type }}" name="{{ name }}" value="{{899 value|e }}" size="{{ size }}">900 {%- endmacro %}901902The macro can then be called like a function in the namespace::903904 <p>{{ input('username') }}</p>905 <p>{{ input('password', type='password') }}</p>906907If the macro was defined in a different template, you have to908:ref:`import <import>` it first.909910Inside macros, you have access to three special variables:911912`varargs`913 If more positional arguments are passed to the macro than accepted by the914 macro, they end up in the special `varargs` variable as a list of values.915916`kwargs`917 Like `varargs` but for keyword arguments. All unconsumed keyword918 arguments are stored in this special variable.919920`caller`921 If the macro was called from a :ref:`call<call>` tag, the caller is stored922 in this variable as a callable macro.923924Macros also expose some of their internal details. The following attributes925are available on a macro object:926927`name`928 The name of the macro. ``{{ input.name }}`` will print ``input``.929930`arguments`931 A tuple of the names of arguments the macro accepts.932933`catch_kwargs`934 This is `true` if the macro accepts extra keyword arguments (i.e.: accesses935 the special `kwargs` variable).936937`catch_varargs`938 This is `true` if the macro accepts extra positional arguments (i.e.:939 accesses the special `varargs` variable).940941`caller`942 This is `true` if the macro accesses the special `caller` variable and may943 be called from a :ref:`call<call>` tag.944945If a macro name starts with an underscore, it's not exported and can't946be imported.947Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 948–950why, one step back948Due to how scopes work in Jinja, a macro in a child template does not949override a macro in a parent template. The following will output950"LAYOUT", not "CHILD".update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 951why, one step back951Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 952–965why, one step back952.. code-block:: jinja953 :caption: ``layout.txt``954955 {% macro foo() %}LAYOUT{% endmacro %}956 {% block body %}{% endblock %}957958.. code-block:: jinja959 :caption: ``child.txt``960961 {% extends 'layout.txt' %}962 {% macro foo() %}CHILD{% endmacro %}963 {% block body %}{{ foo() }}{% endblock %}964965update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 966–1023why, one step back966.. _call:967968Call969~~~~970971In some cases it can be useful to pass a macro to another macro. For this972purpose, you can use the special `call` block. The following example shows973a macro that takes advantage of the call functionality and how it can be974used::975976 {% 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 %}984985 {% call render_dialog('Hello World') %}986 This is a simple dialog rendered by using a macro and987 a call block.988 {% endcall %}989990It's also possible to pass arguments back to the call block. This makes it991useful as a replacement for loops. Generally speaking, a call block works992exactly like a macro without a name.993994Here's an example of how a call block can be used with arguments::995996 {% 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 %}10031004 {% 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 %}101210131014Filters1015~~~~~~~10161017Filter sections allow you to apply regular Jinja filters on a block of1018template data. Just wrap the code in the special `filter` section::10191020 {% filter upper %}1021 This text becomes uppercase1022 {% endfilter %}1023Merge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1024why, one step back1024Filters that accept arguments can be called like this::update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1025why, one step back1025Merge branch '3.1.x'David Lordbefore adoption5d9ece6
lines 1026–1027why, one step back1026 {% filter center(100) %}Center this{% endfilter %}1027update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1028–1088why, one step back1028.. _assignments:10291030Assignments1031~~~~~~~~~~~10321033Inside code blocks, you can also assign values to variables. Assignments at1034top level (outside of blocks, macros or loops) are exported from the template1035like top level macros and can be imported by other templates.10361037Assignments use the `set` tag and can have multiple targets::10381039 {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}1040 {% set key, value = call_something() %}10411042.. admonition:: Scoping Behavior10431044 Please keep in mind that it is not possible to set variables inside a1045 block and have them show up outside of it. This also applies to1046 loops. The only exception to that rule are if statements which do not1047 introduce a scope. As a result the following template is not going1048 to do what you might expect::10491050 {% set iterated = false %}1051 {% for item in seq %}1052 {{ item }}1053 {% set iterated = true %}1054 {% endfor %}1055 {% if not iterated %} did not iterate {% endif %}10561057 It is not possible with Jinja syntax to do this. Instead use1058 alternative constructs like the loop else block or the special `loop`1059 variable::10601061 {% for item in seq %}1062 {{ item }}1063 {% else %}1064 did not iterate1065 {% endfor %}10661067 As of version 2.10 more complex use cases can be handled using namespace1068 objects which allow propagating of changes across scopes::10691070 {% 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 }}10781079 Note that the ``obj.attr`` notation in the `set` tag is only allowed for1080 namespace objects; attempting to assign an attribute on any other object1081 will raise an exception.10821083 .. versionadded:: 2.10 Added support for namespace objects108410851086Block Assignments1087~~~~~~~~~~~~~~~~~1088Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1089–1091why, one step back1089It's possible to use `set` as a block to assign the content of the block to a1090variable. This can be used to create multi-line strings, since Jinja doesn't1091support Python's triple quotes (``"""``, ``'''``).update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1092why, one step back1092Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1093–1094why, one step back1093Instead of using an equals sign and a value, you only write the variable name,1094and everything until ``{% endset %}`` is captured.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1095why, one step back1095Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1096why, one step back1096.. code-block:: jinjaupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1097–1102why, one step back10971098 {% set navigation %}1099 <li><a href="/">Index</a>1100 <li><a href="/downloads">Downloads</a>1101 {% endset %}1102Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1103why, one step back1103Filters applied to the variable name will be applied to the block's content.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1104why, one step back1104Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1105why, one step back1105.. code-block:: jinjaupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1106–1111why, one step back11061107 {% set reply | wordwrap %}1108 You wrote:1109 {{ message }}1110 {% endset %}1111Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1112why, one step back1112.. versionadded:: 2.8update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1113why, one step back1113Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1114–1117why, one step back1114.. versionchanged:: 2.1011151116 Block assignment supports filters.1117update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1118–1142why, one step back1118.. _extends:11191120Extends1121~~~~~~~11221123The `extends` tag can be used to extend one template from another. You can1124have multiple `extends` tags in a file, but only one of them may be executed at1125a time.11261127See the section about :ref:`template-inheritance` above.112811291130.. _blocks:11311132Blocks1133~~~~~~11341135Blocks are used for inheritance and act as both placeholders and replacements1136at the same time. They are documented in detail in the1137:ref:`template-inheritance` section.113811391140Include1141~~~~~~~1142Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1143–1144why, one step back1143The ``include`` tag renders another template and outputs the result into1144the current template.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1145why, one step back1145Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1146–1147why, one step back1146.. code-block:: jinja1147update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1148why, one step back1148 {% include 'header.html' %}Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
line 1149why, one step back1149 Body goes here.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1150–1151why, one step back1150 {% include 'footer.html' %}1151Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1152–1155why, one step back1152The included template has access to context of the current template by1153default. Use ``without context`` to use a separate context instead.1154``with context`` is also valid, but is the default behavior. See1155:ref:`import-visibility`.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1156why, one step back1156Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1157–1159why, one step back1157The included template can ``extend`` another template and override1158blocks in that template. However, the current template cannot override1159any blocks that the included template outputs.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1160why, one step back1160Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1161–1166why, one step back1161Use ``ignore missing`` to ignore the statement if the template does not1162exist. It must be placed *before* a context visibility statement.11631164.. code-block:: jinja11651166 {% include "sidebar.html" without context %}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1167–1170why, one step back1167 {% include "sidebar.html" ignore missing %}1168 {% include "sidebar.html" ignore missing with context %}1169 {% include "sidebar.html" ignore missing without context %}1170Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
lines 1171–1173why, one step back1171If a list of templates is given, each will be tried in order until one1172is not missing. This can be used with ``ignore missing`` to ignore if1173none of the templates exist.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1174why, one step back1174Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
line 1175why, one step back1175.. code-block:: jinjaupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1176–1179why, one step back11761177 {% include ['page_detailed.html', 'page.html'] %}1178 {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}1179Merge pull request #1617 from pallets/docs-proseDavid Lordbefore adoption3a050b1
line 1180why, one step back1180A variable, with either a template name or template object, can also beMerge branch '3.1.x'David Lordbefore adoption36b601f
line 1181why, one step back1181passed to the statement.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1182–1376why, one step back11821183.. _import:11841185Import1186~~~~~~11871188Jinja supports putting often used code into macros. These macros can go into1189different templates and get imported from there. This works similarly to the1190import statements in Python. It's important to know that imports are cached1191and imported templates don't have access to the current template variables,1192just the globals by default. For more details about context behavior of1193imports and includes, see :ref:`import-visibility`.11941195There are two ways to import templates. You can import a complete template1196into a variable or request specific macros / exported variables from it.11971198Imagine we have a helper module that renders forms (called `forms.html`)::11991200 {% macro input(name, value='', type='text') -%}1201 <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">1202 {%- endmacro %}12031204 {%- macro textarea(name, value='', rows=10, cols=40) -%}1205 <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols1206 }}">{{ value|e }}</textarea>1207 {%- endmacro %}12081209The easiest and most flexible way to access a template's variables1210and macros is to import the whole template module into a variable.1211That way, you can access the attributes::12121213 {% 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>122112221223Alternatively, you can import specific names from a template into the current1224namespace::12251226 {% 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>12341235Macros and variables starting with one or more underscores are private and1236cannot be imported.12371238.. versionchanged:: 2.41239 If a template object was passed to the template context, you can1240 import from that object.124112421243.. _import-visibility:12441245Import Context Behavior1246-----------------------12471248By default, included templates are passed the current context and imported1249templates are not. The reason for this is that imports, unlike includes,1250are cached; as imports are often used just as a module that holds macros.12511252This behavior can be changed explicitly: by adding `with context`1253or `without context` to the import/include directive, the current context1254can be passed to the template and caching is disabled automatically.12551256Here are two examples::12571258 {% from 'forms.html' import input with context %}1259 {% include 'header.html' without context %}12601261.. admonition:: Note12621263 In Jinja 2.0, the context that was passed to the included template1264 did not include variables defined in the template. As a matter of1265 fact, this did not work::12661267 {% for box in boxes %}1268 {% include "render_box.html" %}1269 {% endfor %}12701271 The included template ``render_box.html`` is *not* able to access1272 `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able1273 to do so.127412751276.. _expressions:12771278Expressions1279-----------12801281Jinja allows basic expressions everywhere. These work very similarly to1282regular Python; even if you're not working with Python1283you should feel comfortable with it.12841285Literals1286~~~~~~~~12871288The simplest form of expressions are literals. Literals are representations1289for Python objects such as strings and numbers. The following literals exist:12901291``"Hello World"``1292 Everything between two double or single quotes is a string. They are1293 useful whenever you need a string in the template (e.g. as1294 arguments to function calls and filters, or just to extend or include a1295 template).12961297``42`` / ``123_456``1298 Integers are whole numbers without a decimal part. The '_' character1299 can be used to separate groups for legibility.13001301``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 or1304 lower case 'e' to indicate the exponent part. The '_' character can1305 be used to separate groups for legibility, but cannot be used in the1306 exponent part.13071308``['list', 'of', 'objects']``1309 Everything between two brackets is a list. Lists are useful for storing1310 sequential data to be iterated over. For example, you can easily1311 create a list of links using lists and tuples for (and with) a for loop::13121313 <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>13191320``('tuple', 'of', 'values')``1321 Tuples are like lists that cannot be modified ("immutable"). If a tuple1322 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.13251326``{'dict': 'of', 'key': 'and', 'value': 'pairs'}``1327 A dict in Python is a structure that combines keys and values. Keys must1328 be unique and always have exactly one value. Dicts are rarely used in1329 templates; they are useful in some rare cases such as the :func:`xmlattr`1330 filter.13311332``true`` / ``false``1333 ``true`` is always true and ``false`` is always false.13341335.. admonition:: Note13361337 The special constants `true`, `false`, and `none` are indeed lowercase.1338 Because that caused confusion in the past, (`True` used to expand1339 to an undefined variable that was considered false),1340 all three can now also be written in title case1341 (`True`, `False`, and `None`).1342 However, for consistency, (all Jinja identifiers are lowercase)1343 you should use the lowercase versions.13441345Math1346~~~~13471348Jinja allows you to calculate with values. This is rarely useful in templates1349but exists for completeness' sake. The following operators are supported:13501351``+``1352 Adds two objects together. Usually the objects are numbers, but if both are1353 strings or lists, you can concatenate them this way. This, however, is not1354 the preferred way to concatenate strings! For string concatenation, have1355 a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``.13561357``-``1358 Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.13591360``/``1361 Divide two numbers. The return value will be a floating point number.1362 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.13631364``//``1365 Divide two numbers and return the truncated integer result.1366 ``{{ 20 // 7 }}`` is ``2``.13671368``%``1369 Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.13701371``*``1372 Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would1373 return ``4``. This can also be used to repeat a string multiple times.1374 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.13751376``**``Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 1377–1389why, one step back1377 Raise the left operand to the power of the right operand.1378 ``{{ 2**3 }}`` would return ``8``.13791380 Unlike Python, chained pow is evaluated left to right.1381 ``{{ 3**3**3 }}`` is evaluated as ``(3**3)**3`` in Jinja, but would1382 be evaluated as ``3**(3**3)`` in Python. Use parentheses in Jinja1383 to be explicit about what order you want. It is usually preferable1384 to do extended math in Python and pass the results to ``render``1385 rather than doing it in the template.13861387 This behavior may be changed in the future to match Python, if it's1388 possible to introduce an upgrade path.1389update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1390–1414why, one step back13901391Comparisons1392~~~~~~~~~~~13931394``==``1395 Compares two objects for equality.13961397``!=``1398 Compares two objects for inequality.13991400``>``1401 ``true`` if the left hand side is greater than the right hand side.14021403``>=``1404 ``true`` if the left hand side is greater or equal to the right hand side.14051406``<``1407 ``true`` if the left hand side is lower than the right hand side.14081409``<=``1410 ``true`` if the left hand side is lower or equal to the right hand side.14111412Logic1413~~~~~1414Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1415–1416why, one step back1415For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be1416useful to combine multiple expressions.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1417–1418why, one step back14171418``and``Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1419–1421why, one step back1419 For ``x and y``, if ``x`` is false, then the value is ``x``, else ``y``. In1420 a boolean context, this will be treated as ``True`` if both operands are1421 truthy.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1422–1423why, one step back14221423``or``Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1424–1426why, one step back1424 For ``x or y``, if ``x`` is true, then the value is ``x``, else ``y``. In a1425 boolean context, this will be treated as ``True`` if at least one operand is1426 truthy.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1427–1428why, one step back14271428``not``Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1429–1430why, one step back1429 For ``not x``, if ``x`` is false, then the value is ``True``, else1430 ``False``.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1431why, one step back1431Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1432–1434why, one step back1432 Prefer negating ``is`` and ``in`` using their infix notation:1433 ``foo is not bar`` instead of ``not foo is bar``; ``foo not in bar`` instead1434 of ``not foo in bar``. All other expressions require prefix notation:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1435–1436why, one step back1435 ``not (foo and bar).``1436Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1437–1439why, one step back1437``(expr)``1438 Parentheses group an expression. This is used to change evaluation order, or1439 to make a long expression easier to read or less ambiguous.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1440why, one step back1440Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1441why, one step back1441update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1442–1455why, one step back1442Other Operators1443~~~~~~~~~~~~~~~14441445The following operators are very useful but don't fit into any of the other1446two categories:14471448``in``1449 Perform a sequence / mapping containment test. Returns true if the left1450 operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for1451 example, return true.14521453``is``1454 Performs a :ref:`test <tests>`.1455Merge pull request #1226 from geographika/patch-1David Lordbefore adoption851f7af
line 1456why, one step back1456``|`` (pipe, vertical bar)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1457–1458why, one step back1457 Applies a :ref:`filter <filters>`.1458Merge pull request #1226 from geographika/patch-1David Lordbefore adoption851f7af
line 1459why, one step back1459``~`` (tilde)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1460–1483why, one step back1460 Converts all operands into strings and concatenates them.14611462 ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set1463 to ``'John'``) ``Hello John!``.14641465``()``1466 Call a callable: ``{{ post.render() }}``. Inside of the parentheses you1467 can use positional arguments and keyword arguments like in Python:14681469 ``{{ post.render(user, full=true) }}``.14701471``.`` / ``[]``1472 Get an attribute of an object. (See :ref:`variables`)147314741475.. _if-expression:14761477If Expression1478~~~~~~~~~~~~~14791480It is also possible to use inline `if` expressions. These are useful in some1481situations. For example, you can use this to extend from one template if a1482variable is defined, otherwise from the default layout template::1483Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3
line 1484why, one step back1484 {% extends layout_template if layout_template is defined else 'default.html' %}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1485–1538why, one step back14851486The general syntax is ``<do something> if <something is true> else <do1487something else>``.14881489The `else` part is optional. If not provided, the else block implicitly1490evaluates into an :class:`Undefined` object (regardless of what ``undefined``1491in the environment is set to):14921493.. code-block:: jinja14941495 {{ "[{}]".format(page.title) if page.title }}149614971498.. _python-methods:14991500Python Methods1501~~~~~~~~~~~~~~15021503You can also use any of the methods defined on a variable's type.1504The value returned from the method invocation is used as the value of the expression.1505Here is an example that uses methods defined on strings (where ``page.title`` is a string):15061507.. code-block:: text15081509 {{ page.title.capitalize() }}15101511This works for methods on user-defined types. For example, if variable1512``f`` of type ``Foo`` has a method ``bar`` defined on it, you can do the1513following:15141515.. code-block:: text15161517 {{ f.bar(value) }}15181519Operator methods also work as expected. For example, ``%`` implements1520printf-style for strings:15211522.. code-block:: text15231524 {{ "Hello, %s!" % name }}15251526Although you should prefer the ``.format`` method for that case (which1527is a bit contrived in the context of rendering a template):15281529.. code-block:: text15301531 {{ "Hello, {}!".format(name) }}153215331534.. _builtin-filters:15351536List of Builtin Filters1537-----------------------1538Merge pull request #1398 from pallets/docs-filter-anchorDavid Lordbefore adoptionf04bde8
lines 1539–1540why, one step back1539.. py:currentmodule:: jinja-filters1540update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1541–1548why, one step back1541.. jinja:filters:: jinja2.defaults.DEFAULT_FILTERS154215431544.. _builtin-tests:15451546List of Builtin Tests1547---------------------1548Merge pull request #1398 from pallets/docs-filter-anchorDavid Lordbefore adoptionf04bde8
lines 1549–1550why, one step back1549.. py:currentmodule:: jinja-tests1550update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1551–1560why, one step back1551.. jinja:tests:: jinja2.defaults.DEFAULT_TESTS155215531554.. _builtin-globals:15551556List of Global Functions1557------------------------15581559The following functions are available in the global scope by default:1560Merge pull request #1398 from pallets/docs-filter-anchorDavid Lordbefore adoptionf04bde8
lines 1561–1562why, one step back1561.. py:currentmodule:: jinja-globals1562update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1563–1623why, one step back1563.. function:: range([start,] stop[, step])15641565 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.15721573 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 to1575 render three empty items to enforce a height with CSS::15761577 <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>15851586.. function:: lipsum(n=5, html=True, min=20, max=100)15871588 Generates some lorem ipsum for the template. By default, five paragraphs1589 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 simple1591 contents for layout testing.15921593.. function:: dict(\**items)15941595 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same1596 as ``dict(foo='bar')``.15971598.. class:: cycler(\*items)15991600 Cycle through values by yielding them one at a time, then restarting1601 once the end is reached.16021603 Similar to ``loop.cycle``, but can be used outside loops or across1604 multiple loops. For example, render a list of folders and files in a1605 list, alternating giving them "odd" and "even" classes.16061607 .. code-block:: html+jinja16081609 {% 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>16181619 :param items: Each positional argument will be yielded in the order1620 given for each cycle.16211622 .. versionadded:: 2.11623Merge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1624why, one step back1624 .. property:: currentupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1625–1680why, one step back16251626 Return the current item. Equivalent to the item that will be1627 returned next time :meth:`next` is called.16281629 .. method:: next()16301631 Return the current item, then advance :attr:`current` to the1632 next item.16331634 .. method:: reset()16351636 Resets the current item to the first item.16371638.. class:: joiner(sep=', ')16391640 A tiny helper that can be used to "join" multiple sections. A joiner is1641 passed a string and will return that string every time it's called, except1642 the first time (in which case it returns an empty string). You can1643 use this to join things::16441645 {% 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 %}16551656 .. versionadded:: 2.116571658.. class:: namespace(...)16591660 Creates a new container that allows attribute assignment using the1661 ``{% set %}`` tag::16621663 {% set ns = namespace() %}1664 {% set ns.foo = 'bar' %}16651666 The main purpose of this is to allow carrying a value from within a loop1667 body to an outer scope. Initial values can be provided as a dict, as1668 keyword arguments, or both (same behavior as Python's `dict` constructor)::16691670 {% 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 }}16781679 .. versionadded:: 2.101680Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1681–1682why, one step back1681 .. versionchanged:: 3.21682 Namespace attributes can be assigned to in multiple assignment.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1683why, one step back1683Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1684why, one step back1684update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1685–1686why, one step back1685Extensions1686----------Merge pull request #1398 from pallets/docs-filter-anchorDavid Lordbefore adoptionf04bde8
lines 1687–1688why, one step back16871688.. py:currentmodule:: jinja2update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1689–1770why, one step back16891690The following sections cover the built-in Jinja extensions that may be1691enabled by an application. An application could also provide further1692extensions not covered by this documentation; in which case there should1693be a separate document explaining said :ref:`extensions1694<jinja-extensions>`.169516961697.. _i18n-in-templates:16981699i18n1700~~~~17011702If the :ref:`i18n-extension` is enabled, it's possible to mark text in1703the template as translatable. To mark a section as translatable, use a1704``trans`` block:17051706.. code-block:: jinja17071708 {% trans %}Hello, {{ user }}!{% endtrans %}17091710Inside the block, no statements are allowed, only text and simple1711variable tags.17121713Variable tags can only be a name, not attribute access, filters, or1714other expressions. To use an expression, bind it to a name in the1715``trans`` tag for use in the block.17161717.. code-block:: jinja17181719 {% trans user=user.username %}Hello, {{ user }}!{% endtrans %}17201721To bind more than one expression, separate each with a comma (``,``).17221723.. code-block:: jinja17241725 {% trans book_title=book.title, author=author.name %}1726 This is {{ book_title }} by {{ author }}1727 {% endtrans %}17281729To pluralize, specify both the singular and plural forms separated by1730the ``pluralize`` tag.17311732.. code-block:: jinja17331734 {% trans count=list|length %}1735 There is {{ count }} {{ name }} object.1736 {% pluralize %}1737 There are {{ count }} {{ name }} objects.1738 {% endtrans %}17391740By default, the first variable in a block is used to determine whether1741to use singular or plural form. If that isn't correct, specify the1742variable used for pluralizing as a parameter to ``pluralize``.17431744.. code-block:: jinja17451746 {% trans ..., user_count=users|length %}...1747 {% pluralize user_count %}...{% endtrans %}17481749When translating blocks of text, whitespace and linebreaks result in1750hard to read and error-prone translation strings. To avoid this, a trans1751block can be marked as trimmed, which will replace all linebreaks and1752the whitespace surrounding them with a single space and remove leading1753and trailing whitespace.17541755.. code-block:: jinja17561757 {% trans trimmed book_title=book.title %}1758 This is {{ book_title }}.1759 You should read it!1760 {% endtrans %}17611762This results in ``This is %(book_title)s. You should read it!`` in the1763translation file.17641765If trimming is enabled globally, the ``notrimmed`` modifier can be used1766to disable it for a block.17671768.. versionadded:: 2.101769 The ``trimmed`` and ``notrimmed`` modifiers have been added.1770Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c
lines 1771–1789why, one step back1771If the translation depends on the context that the message appears in,1772the ``pgettext`` and ``npgettext`` functions take a ``context`` string1773as the first argument, which is used to select the appropriate1774translation. To specify a context with the ``{% trans %}`` tag, provide1775a string as the first token after ``trans``.17761777.. code-block:: jinja17781779 {% trans "fruit" %}apple{% endtrans %}1780 {% trans "fruit" trimmed count -%}1781 1 apple1782 {%- pluralize -%}1783 {{ count }} apples1784 {%- endtrans %}17851786.. versionadded:: 3.11787 A context can be passed to the ``trans`` tag to use ``pgettext`` and1788 ``npgettext``.1789update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1790–1791why, one step back1790It's possible to translate strings in expressions with these functions:1791Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c
lines 1792–1793why, one step back1792- ``_(message)``: Alias for ``gettext``.1793- ``gettext(message)``: Translate a message.Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1794why, one step back1794- ``ngettext(singular, plural, n)``: Translate a singular or pluralMerge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c
lines 1795–1799why, one step back1795 message based on a count variable.1796- ``pgettext(context, message)``: Like ``gettext()``, but picks the1797 translation based on the context string.1798- ``npgettext(context, singular, plural, n)``: Like ``npgettext()``,1799 but picks the translation based on the context string.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1800–1965why, one step back18001801You can print a translated string like this:18021803.. code-block:: jinja18041805 {{ _("Hello, World!") }}18061807To use placeholders, use the ``format`` filter.18081809.. code-block:: jinja18101811 {{ _("Hello, %(user)s!")|format(user=user.username) }}18121813Always use keyword arguments to ``format``, as other languages may not1814use the words in the same order.18151816If :ref:`newstyle-gettext` calls are activated, using placeholders is1817easier. Formatting is part of the ``gettext`` call instead of using the1818``format`` filter.18191820.. sourcecode:: jinja18211822 {{ gettext('Hello World!') }}1823 {{ gettext('Hello %(name)s!', name='World') }}1824 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}18251826The ``ngettext`` function's format string automatically receives the1827count as a ``num`` parameter in addition to the given parameters.182818291830Expression Statement1831~~~~~~~~~~~~~~~~~~~~18321833If the expression-statement extension is loaded, a tag called `do` is available1834that works exactly like the regular variable expression (``{{ ... }}``); except1835it doesn't print anything. This can be used to modify lists::18361837 {% do navigation.append('a string') %}183818391840Loop Controls1841~~~~~~~~~~~~~18421843If the application enables the :ref:`loopcontrols-extension`, it's possible to1844use `break` and `continue` in loops. When `break` is reached, the loop is1845terminated; if `continue` is reached, the processing is stopped and continues1846with the next iteration.18471848Here's a loop that skips every second item::18491850 {% for user in users %}1851 {%- if loop.index is even %}{% continue %}{% endif %}1852 ...1853 {% endfor %}18541855Likewise, a loop that stops processing after the 10th iteration::18561857 {% for user in users %}1858 {%- if loop.index >= 10 %}{% break %}{% endif %}1859 {%- endfor %}18601861Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 01862(See: :ref:`for-loop`).186318641865Debug Statement1866~~~~~~~~~~~~~~~18671868If the :ref:`debug-extension` is enabled, a ``{% debug %}`` tag will be1869available to dump the current context as well as the available filters1870and tests. This is useful to see what's available to use in the template1871without setting up a debugger.18721873.. code-block:: html+jinja18741875 <pre>{% debug %}</pre>18761877.. code-block:: text18781879 {'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']}188618871888With Statement1889~~~~~~~~~~~~~~18901891.. versionadded:: 2.318921893The with statement makes it possible to create a new inner scope.1894Variables set within this scope are not visible outside of the scope.18951896With in a nutshell::18971898 {% with %}1899 {% set foo = 42 %}1900 {{ foo }} foo is 42 here1901 {% endwith %}1902 foo is not visible here any longer19031904Because it is common to set variables at the beginning of the scope,1905you can do that within the `with` statement. The following two examples1906are equivalent::19071908 {% with foo = 42 %}1909 {{ foo }}1910 {% endwith %}19111912 {% with %}1913 {% set foo = 42 %}1914 {{ foo }}1915 {% endwith %}19161917An important note on scoping here. In Jinja versions before 2.9 the1918behavior of referencing one variable to another had some unintended1919consequences. In particular one variable could refer to another defined1920in the same with block's opening statement. This caused issues with the1921cleaned up scoping behavior and has since been improved. In particular1922in newer Jinja versions the following code always refers to the variable1923`a` from outside the `with` block::19241925 {% with a={}, b=a.attribute %}...{% endwith %}19261927In earlier Jinja versions the `b` attribute would refer to the results of1928the first attribute. If you depend on this behavior you can rewrite it to1929use the ``set`` tag::19301931 {% with a={} %}1932 {% set b = a.attribute %}1933 {% endwith %}19341935.. admonition:: Extension19361937 In older versions of Jinja (before 2.9) it was required to enable this1938 feature with an extension. It's now enabled by default.19391940.. _autoescape-overrides:19411942Autoescape Overrides1943--------------------19441945.. versionadded:: 2.419461947If you want you can activate and deactivate the autoescaping from within1948the templates.19491950Example::19511952 {% autoescape true %}1953 Autoescaping is active within this block1954 {% endautoescape %}19551956 {% autoescape false %}1957 Autoescaping is inactive within this block1958 {% endautoescape %}19591960After an `endautoescape` the behavior is reverted to what it was before.19611962.. admonition:: Extension19631964 In older versions of Jinja (before 2.9) it was required to enable this1965 feature with an extension. It's now enabled by default.