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