PK Default page
One Hat Cyber Team
  • Dir : ~/usr/share/doc/python3-jinja2/html/_sources/
  • Edit File: templates.rst.txt
    {%- endmacro %} The easiest and most flexible way to access a template's variables and macros is to import the whole template module into a variable. That way, you can access the attributes:: {% import 'forms.html' as forms %}
    Username
    {{ forms.input('username') }}
    Password
    {{ forms.input('password', type='password') }}

    {{ forms.textarea('comment') }}

    Alternatively, you can import specific names from a template into the current namespace:: {% from 'forms.html' import input as input_field, textarea %}
    Username
    {{ input_field('username') }}
    Password
    {{ input_field('password', type='password') }}

    {{ textarea('comment') }}

    Macros and variables starting with one or more underscores are private and cannot be imported. .. versionchanged:: 2.4 If a template object was passed to the template context, you can import from that object. .. _import-visibility: Import Context Behavior ----------------------- By default, included templates are passed the current context and imported templates are not. The reason for this is that imports, unlike includes, are cached; as imports are often used just as a module that holds macros. This behavior can be changed explicitly: by adding `with context` or `without context` to the import/include directive, the current context can be passed to the template and caching is disabled automatically. Here are two examples:: {% from 'forms.html' import input with context %} {% include 'header.html' without context %} .. admonition:: Note In Jinja 2.0, the context that was passed to the included template did not include variables defined in the template. As a matter of fact, this did not work:: {% for box in boxes %} {% include "render_box.html" %} {% endfor %} The included template ``render_box.html`` is *not* able to access `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able to do so. .. _expressions: Expressions ----------- Jinja allows basic expressions everywhere. These work very similarly to regular Python; even if you're not working with Python you should feel comfortable with it. Literals ~~~~~~~~ The simplest form of expressions are literals. Literals are representations for Python objects such as strings and numbers. The following literals exist: "Hello World": Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template). 42 / 42.23: Integers and floating point numbers are created by just writing the number down. If a dot is present, the number is a float, otherwise an integer. Keep in mind that, in Python, ``42`` and ``42.0`` are different (``int`` and ``float``, respectively). ['list', 'of', 'objects']: Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop:: ('tuple', 'of', 'values'): Tuples are like lists that cannot be modified ("immutable"). If a tuple only has one item, it must be followed by a comma (``('1-tuple',)``). Tuples are usually used to represent items of two or more elements. See the list example above for more details. {'dict': 'of', 'key': 'and', 'value': 'pairs'}: A dict in Python is a structure that combines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in templates; they are useful in some rare cases such as the :func:`xmlattr` filter. true / false: true is always true and false is always false. .. admonition:: Note The special constants `true`, `false`, and `none` are indeed lowercase. Because that caused confusion in the past, (`True` used to expand to an undefined variable that was considered false), all three can now also be written in title case (`True`, `False`, and `None`). However, for consistency, (all Jinja identifiers are lowercase) you should use the lowercase versions. Math ~~~~ Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness' sake. The following operators are supported: \+ Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``. \- Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``. / Divide two numbers. The return value will be a floating point number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. (Just like ``from __future__ import division``.) // Divide two numbers and return the truncated integer result. ``{{ 20 // 7 }}`` is ``2``. % Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``. \* Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would return ``4``. This can also be used to repeat a string multiple times. ``{{ '=' * 80 }}`` would print a bar of 80 equal signs. \** Raise the left operand to the power of the right operand. ``{{ 2**3 }}`` would return ``8``. Comparisons ~~~~~~~~~~~ == Compares two objects for equality. != Compares two objects for inequality. > `true` if the left hand side is greater than the right hand side. >= `true` if the left hand side is greater or equal to the right hand side. < `true` if the left hand side is lower than the right hand side. <= `true` if the left hand side is lower or equal to the right hand side. Logic ~~~~~ For `if` statements, `for` filtering, and `if` expressions, it can be useful to combine multiple expressions: and Return true if the left and the right operand are true. or Return true if the left or the right operand are true. not negate a statement (see below). (expr) group an expression. .. admonition:: Note The ``is`` and ``in`` operators support negation using an infix notation, too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar`` and ``not foo in bar``. All other expressions require a prefix notation: ``not (foo and bar).`` Other Operators ~~~~~~~~~~~~~~~ The following operators are very useful but don't fit into any of the other two categories: in Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for example, return true. is Performs a :ref:`test `. \| Applies a :ref:`filter `. ~ Converts all operands into strings and concatenates them. ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set to ``'John'``) ``Hello John!``. () Call a callable: ``{{ post.render() }}``. Inside of the parentheses you can use positional arguments and keyword arguments like in Python: ``{{ post.render(user, full=true) }}``. . / [] Get an attribute of an object. (See :ref:`variables`) .. _if-expression: If Expression ~~~~~~~~~~~~~ It is also possible to use inline `if` expressions. These are useful in some situations. For example, you can use this to extend from one template if a variable is defined, otherwise from the default layout template:: {% extends layout_template if layout_template is defined else 'master.html' %} The general syntax is `` if else ``. The `else` part is optional. If not provided, the else block implicitly evaluates into an undefined object:: .. sourcecode:: jinja {{ '[%s]' % page.title if page.title }} .. _builtin-filters: List of Builtin Filters ----------------------- .. jinjafilters:: .. _builtin-tests: List of Builtin Tests --------------------- .. jinjatests:: .. _builtin-globals: List of Global Functions ------------------------ The following functions are available in the global scope by default: .. function:: range([start,] stop[, step]) Return a list containing an arithmetic progression of integers. ``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``; start (!) defaults to ``0``. When step is given, it specifies the increment (or decrement). For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``. The end point is omitted! These are exactly the valid indices for a list of 4 elements. This is useful to repeat a template block multiple times, e.g. to fill a list. Imagine you have 7 users in the list but you want to render three empty items to enforce a height with CSS::
      {% for user in users %}
    • {{ user.username }}
    • {% endfor %} {% for number in range(10 - users|count) %}
    • ...
    • {% endfor %}
    .. function:: lipsum(n=5, html=True, min=20, max=100) Generates some lorem ipsum for the template. By default, five paragraphs of HTML are generated with each paragraph between 20 and 100 words. If html is False, regular text is returned. This is useful to generate simple contents for layout testing. .. function:: dict(\**items) A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same as ``dict(foo='bar')``. .. class:: cycler(\*items) The cycler allows you to cycle among values similar to how `loop.cycle` works. Unlike `loop.cycle`, you can use this cycler outside of loops or over multiple loops. This can be very useful if you want to show a list of folders and files with the folders on top but both in the same list with alternating row colors. The following example shows how `cycler` can be used:: {% set row_class = cycler('odd', 'even') %}
      {% for folder in folders %}
    • {{ folder|e }}
    • {% endfor %} {% for filename in files %}
    • {{ filename|e }}
    • {% endfor %}
    A cycler has the following attributes and methods: .. method:: reset() Resets the cycle to the first item. .. method:: next() Goes one item ahead and returns the then-current item. .. attribute:: current Returns the current item. .. versionadded:: 2.1 .. class:: joiner(sep=', ') A tiny helper that can be used to "join" multiple sections. A joiner is passed a string and will return that string every time it's called, except the first time (in which case it returns an empty string). You can use this to join things:: {% set pipe = joiner("|") %} {% if categories %} {{ pipe() }} Categories: {{ categories|join(", ") }} {% endif %} {% if author %} {{ pipe() }} Author: {{ author() }} {% endif %} {% if can_edit %} {{ pipe() }} Edit {% endif %} .. versionadded:: 2.1 .. class:: namespace(...) Creates a new container that allows attribute assignment using the ``{% set %}`` tag:: {% set ns = namespace() %} {% set ns.foo = 'bar' %} The main purpose of this is to allow carrying a value from within a loop body to an outer scope. Initial values can be provided as a dict, as keyword arguments, or both (same behavior as Python's `dict` constructor):: {% set ns = namespace(found=false) %} {% for item in items %} {% if item.check_something() %} {% set ns.found = true %} {% endif %} * {{ item.title }} {% endfor %} Found item having something: {{ ns.found }} .. versionadded:: 2.10 Extensions ---------- The following sections cover the built-in Jinja2 extensions that may be enabled by an application. An application could also provide further extensions not covered by this documentation; in which case there should be a separate document explaining said :ref:`extensions `. .. _i18n-in-templates: i18n ~~~~ If the i18n extension is enabled, it's possible to mark parts in the template as translatable. To mark a section as translatable, you can use `trans`::

    {% trans %}Hello {{ user }}!{% endtrans %}

    To translate a template expression --- say, using template filters, or by just accessing an attribute of an object --- you need to bind the expression to a name for use within the translation block::

    {% trans user=user.username %}Hello {{ user }}!{% endtrans %}

    If you need to bind more than one expression inside a `trans` tag, separate the pieces with a comma (``,``):: {% trans book_title=book.title, author=author.name %} This is {{ book_title }} by {{ author }} {% endtrans %} Inside trans tags no statements are allowed, only variable tags are. To pluralize, specify both the singular and plural forms with the `pluralize` tag, which appears between `trans` and `endtrans`:: {% trans count=list|length %} There is {{ count }} {{ name }} object. {% pluralize %} There are {{ count }} {{ name }} objects. {% endtrans %} By default, the first variable in a block is used to determine the correct singular or plural form. If that doesn't work out, you can specify the name which should be used for pluralizing by adding it as parameter to `pluralize`:: {% trans ..., user_count=users|length %}... {% pluralize user_count %}...{% endtrans %} When translating longer blocks of text, whitespace and linebreaks result in rather ugly and error-prone translation strings. To avoid this, a trans block can be marked as trimmed which will replace all linebreaks and the whitespace surrounding them with a single space and remove leading/trailing whitespace:: {% trans trimmed book_title=book.title %} This is {{ book_title }}. You should read it! {% endtrans %} If trimming is enabled globally, the `notrimmed` modifier can be used to disable it for a `trans` block. .. versionadded:: 2.10 The `trimmed` and `notrimmed` modifiers have been added. It's also possible to translate strings in expressions. For that purpose, three functions exist: - `gettext`: translate a single string - `ngettext`: translate a pluralizable string - `_`: alias for `gettext` For example, you can easily print a translated string like this:: {{ _('Hello World!') }} To use placeholders, use the `format` filter:: {{ _('Hello %(user)s!')|format(user=user.username) }} For multiple placeholders, always use keyword arguments to `format`, as other languages may not use the words in the same order. .. versionchanged:: 2.5 If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using placeholders is a lot easier: .. sourcecode:: html+jinja {{ gettext('Hello World!') }} {{ gettext('Hello %(name)s!', name='World') }} {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} Note that the `ngettext` function's format string automatically receives the count as a `num` parameter in addition to the regular parameters. Expression Statement ~~~~~~~~~~~~~~~~~~~~ If the expression-statement extension is loaded, a tag called `do` is available that works exactly like the regular variable expression (``{{ ... }}``); except it doesn't print anything. This can be used to modify lists:: {% do navigation.append('a string') %} Loop Controls ~~~~~~~~~~~~~ If the application enables the :ref:`loopcontrols-extension`, it's possible to use `break` and `continue` in loops. When `break` is reached, the loop is terminated; if `continue` is reached, the processing is stopped and continues with the next iteration. Here's a loop that skips every second item:: {% for user in users %} {%- if loop.index is even %}{% continue %}{% endif %} ... {% endfor %} Likewise, a loop that stops processing after the 10th iteration:: {% for user in users %} {%- if loop.index >= 10 %}{% break %}{% endif %} {%- endfor %} Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0 (See: :ref:`for-loop`). With Statement ~~~~~~~~~~~~~~ .. versionadded:: 2.3 The with statement makes it possible to create a new inner scope. Variables set within this scope are not visible outside of the scope. With in a nutshell:: {% with %} {% set foo = 42 %} {{ foo }} foo is 42 here {% endwith %} foo is not visible here any longer Because it is common to set variables at the beginning of the scope, you can do that within the `with` statement. The following two examples are equivalent:: {% with foo = 42 %} {{ foo }} {% endwith %} {% with %} {% set foo = 42 %} {{ foo }} {% endwith %} An important note on scoping here. In Jinja versions before 2.9 the behavior of referencing one variable to another had some unintended consequences. In particular one variable could refer to another defined in the same with block's opening statement. This caused issues with the cleaned up scoping behavior and has since been improved. In particular in newer Jinja2 versions the following code always refers to the variable `a` from outside the `with` block:: {% with a={}, b=a.attribute %}...{% endwith %} In earlier Jinja versions the `b` attribute would refer to the results of the first attribute. If you depend on this behavior you can rewrite it to use the ``set`` tag:: {% with a={} %} {% set b = a.attribute %} {% endwith %} .. admonition:: Extension In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It's now enabled by default. .. _autoescape-overrides: Autoescape Overrides -------------------- .. versionadded:: 2.4 If you want you can activate and deactivate the autoescaping from within the templates. Example:: {% autoescape true %} Autoescaping is active within this block {% endautoescape %} {% autoescape false %} Autoescaping is inactive within this block {% endautoescape %} After an `endautoescape` the behavior is reverted to what it was before. .. admonition:: Extension In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It's now enabled by default.