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