recieves->receives
[jinja2.git] / docs / templates.rst
index 90d4099da1498631c35890802b4aa22d4f7e2105..50b6b7ec1264fdb10b9d03b50509d91999e4cc2e 100644 (file)
@@ -44,7 +44,7 @@ the details later in that document::
 This covers the default settings.  The application developer might have
 changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.
 
-There are two kinds of delimiers. ``{% ... %}`` and ``{{ ... }}``.  The first
+There are two kinds of delimiters. ``{% ... %}`` and ``{{ ... }}``.  The first
 one is used to execute statements such as for-loops or assign values, the
 latter prints the result of the expression to the template.
 
@@ -59,7 +59,7 @@ too.  How a variable looks like, heavily depends on the application providing
 those.
 
 You can use a dot (``.``) to access attributes of a variable, alternative the
-so-called "subscribe" syntax (``[]``) can be used.  The following lines do
+so-called "subscript" syntax (``[]``) can be used.  The following lines do
 the same::
 
     {{ foo.bar }}
@@ -74,12 +74,34 @@ value.  What you can do with that kind of value depends on the application
 configuration, the default behavior is that it evaluates to an empty string
 if printed and that you can iterate over it, but every other operation fails.
 
+.. _notes-on-subscriptions:
+
+.. admonition:: Implementation
+
+    For convenience sake ``foo.bar`` in Jinja2 does the following things on
+    the Python layer:
+
+    -   check if there is an attribute called `bar` on `foo`.
+    -   if there is not, check if there is an item ``'bar'`` in `foo`.
+    -   if there is not, return an undefined object.
+
+    ``foo['bar']`` on the other hand works mostly the same with the a small
+    difference in the order:
+
+    -   check if there is an item ``'bar'`` in `foo`.
+    -   if there is not, check if there is an attribute called `bar` on `foo`.
+    -   if there is not, return an undefined object.
+
+    This is important if an object has an item or attribute with the same
+    name.  Additionally there is the :func:`attr` filter that just looks up
+    attributes.
+
 .. _filters:
 
 Filters
 -------
 
-Variables can by modified by **filters**.  Filters are separated from the
+Variables can be modified by **filters**.  Filters are separated from the
 variable by a pipe symbol (``|``) and may have optional arguments in
 parentheses.  Multiple filters can be chained.  The output of one filter is
 applied to the next.
@@ -87,7 +109,7 @@ applied to the next.
 ``{{ name|striptags|title }}`` for example will remove all HTML Tags from the
 `name` and title-cases it.  Filters that accept arguments have parentheses
 around the arguments, like a function call.  This example will join a list
-by spaces:  ``{{ list|join(', ') }}``.
+by commas:  ``{{ list|join(', ') }}``.
 
 The :ref:`builtin-filters` below describes all the builtin filters.
 
@@ -120,7 +142,7 @@ by default set to ``{# ... #}``.  This is useful to comment out parts of the
 template for debugging or to add information for other template designers or
 yourself::
 
-    {# note: disabled template because we no longer user this
+    {# note: disabled template because we no longer use this
         {% for user in users %}
             ...
         {% endfor %}
@@ -143,22 +165,25 @@ that block::
     {% for item in seq -%}
         {{ item }}
     {%- endfor %}
-    
+
 This will yield all elements without whitespace between them.  If `seq` was
 a list of numbers from ``1`` to ``9`` the output would be ``123456789``.
 
-Note that you must not use a whitespace between the tag and the minus sign:
+If :ref:`line-statements` are enabled they strip leading whitespace
+automatically up to the beginning of the line.
+
+.. admonition:: Note
+
+    You must not use a whitespace between the tag and the minus sign.
+
+    **valid**::
 
-    valid:
         {%- if foo -%}...{% endif %}
 
-    invalid:
+    **invalid**::
 
         {% - if foo - %}...{% endif %}
 
-If :ref:`line-statements` are enabled they strip leading whitespace
-automatically up to the beginning of the line.
-
 
 Escaping
 --------
@@ -212,7 +237,28 @@ precedes it.  For better readability statements that start a block (such as
 
     # for item in seq:
         ...
-    # endif
+    # endfor
+
+
+.. admonition:: Note
+
+    Line statements can span multiple lines if there are open parentheses,
+    braces or brackets::
+
+        <ul>
+        # for href, caption in [('index.html', 'Index'),
+                                ('about.html', 'About')]:
+            <li><a href="{{ href }}">{{ caption }}</a></li>
+        # endfor
+        </ul>
+
+Since Jinja 2.2 line-based comments are available as well.  For example if
+the line-comment prefix is configured to be ``##`` everything from ``##`` to
+the end of the line is ignored (excluding the newline sign)::
+
+    # for item in seq:
+        <li>{{ item }}</li>     ## this comment is ignored
+    # endfor
 
 
 .. _template-inheritance:
@@ -273,7 +319,7 @@ A child template might look like this::
     {% block content %}
         <h1>Index</h1>
         <p class="important">
-          Welcome on my awsome homepage.
+          Welcome on my awesome homepage.
         </p>
     {% endblock %}
 
@@ -309,10 +355,6 @@ If you want to print a block multiple times you can however use the special
     {% block body %}{% endblock %}
 
 
-Unlike Python Jinja does not support multiple inheritance.  So you can only have
-one extends tag called per rendering.
-
-
 Super Blocks
 ~~~~~~~~~~~~
 
@@ -326,6 +368,63 @@ This gives back the results of the parent block::
     {% endblock %}
 
 
+Named Block End-Tags
+~~~~~~~~~~~~~~~~~~~~
+
+Jinja2 allows you to put the name of the block after the end tag for better
+readability::
+
+    {% block sidebar %}
+        {% block inner_sidebar %}
+            ...
+        {% endblock inner_sidebar %}
+    {% endblock sidebar %}
+
+However the name after the `endblock` word must match the block name.
+
+
+Block Nesting and Scope
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Blocks can be nested for more complex layouts.  However per default blocks
+may not access variables from outer scopes::
+
+    {% for item in seq %}
+        <li>{% block loop_item %}{{ item }}{% endblock %}</li>
+    {% endfor %}
+
+This example would output empty ``<li>`` items because `item` is unavailable
+inside the block.  The reason for this is that if the block is replaced by
+a child template a variable would appear that was not defined in the block or
+passed to the context.
+
+Starting with Jinja 2.2 you can explicitly specify that variables are
+available in a block by setting the block to "scoped" by adding the `scoped`
+modifier to a block declaration::
+
+    {% for item in seq %}
+        <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
+    {% endfor %}
+
+When overriding a block the `scoped` modifier does not have to be provided.
+
+
+Template Objects
+~~~~~~~~~~~~~~~~
+
+.. versionchanged:: 2.4
+
+If a template object was passed to the template context you can
+extend from that object as well.  Assuming the calling code passes
+a layout template as `layout_template` to the environment, this
+code works::
+
+    {% extends layout_template %}
+
+Previously the `layout_template` variable had to be a string with
+the layout template's filename for this to work.
+
+
 HTML Escaping
 -------------
 
@@ -430,6 +529,9 @@ each time through the loop by using the special `loop.cycle` helper::
         <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
     {% endfor %}
 
+With Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound
+cycling.  For more information have a look at the :ref:`builtin-globals`.
+
 .. _loop-filtering:
 
 Unlike in Python it's not possible to `break` or `continue` in a loop.  You
@@ -452,7 +554,7 @@ by using `else`::
         <li>{{ user.username|e }}</li>
     {% else %}
         <li><em>no users found</em></li>
-    {% endif %}
+    {% endfor %}
     </ul>
 
 It is also possible to use loops recursively.  This is useful if you are
@@ -509,13 +611,6 @@ Macros are comparable with functions in regular programming languages.  They
 are useful to put often used idioms into reusable functions to not repeat
 yourself.
 
-Macros can be defined in helper templates which then are :ref:`imported
-<import>` or directly in the template where they are used.  There is one big
-difference between those two possibilities.  A macro that is defined in the
-template where it's also used has access to the context passed to the template.
-A macro defined in another template and then imported can only access variables
-defined there or in the global context.
-
 Here a small example of a macro that renders a form element::
 
     {% macro input(name, value='', type='text', size=20) -%}
@@ -569,6 +664,9 @@ are available on a macro object:
     This is `true` if the macro accesses the special `caller` variable and may
     be called from a :ref:`call<call>` tag.
 
+If a macro name starts with an underscore it's not exported and can't
+be imported.
+
 
 .. _call:
 
@@ -595,8 +693,8 @@ used::
     {% endcall %}
 
 It's also possible to pass arguments back to the call block.  This makes it
-useful as replacement for loops.  It is however not possible to call a
-call block with another call block.
+useful as replacement for loops.  Generally speaking a call block works
+exactly like an macro, just that it doesn't have a name.
 
 Here an example of how a call block can be used with arguments::
 
@@ -618,6 +716,17 @@ Here an example of how a call block can be used with arguments::
     {% endcall %}
 
 
+Filters
+~~~~~~~
+
+Filter sections allow you to apply regular Jinja2 filters on a block of
+template data.  Just wrap the code in the special `filter` section::
+
+    {% filter upper %}
+        This text becomes uppercase
+    {% endfilter %}
+
+
 Assignments
 ~~~~~~~~~~~
 
@@ -625,10 +734,10 @@ Inside code blocks you can also assign values to variables.  Assignments at
 top level (outside of blocks, macros or loops) are exported from the template
 like top level macros and can be imported by other templates.
 
-Assignments are just written in code blocks like any other statement just
-without explicit keyword::
+Assignments use the `set` tag and can have multiple targets::
 
-    {% navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
+    {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
+    {% set key, value = call_something() %}
 
 
 Extends
@@ -636,8 +745,7 @@ Extends
 
 The `extends` tag can be used to extend a template from another one.  You
 can have multiple of them in a file but only one of them may be executed
-at the time.  There is no support for multiple inheritance.  See the section
-about :ref:`template-inheritance` above.
+at the time.  See the section about :ref:`template-inheritance` above.
 
 
 Block
@@ -662,6 +770,32 @@ Included templates have access to the variables of the active context by
 default.  For more details about context behavior of imports and includes
 see :ref:`import-visibility`.
 
+From Jinja 2.2 onwards you can mark an include with ``ignore missing`` in
+which case Jinja will ignore the statement if the template to be ignored
+does not exist.  When combined with ``with`` or ``without context`` it has
+to be placed *before* the context visibility statement.  Here some valid
+examples::
+
+    {% include "sidebar.html" ignore missing %}
+    {% include "sidebar.html" ignore missing with context %}
+    {% include "sidebar.html" ignore missing without context %}
+
+.. versionadded:: 2.2
+
+You can also provide a list of templates that are checked for existence
+before inclusion.  The first template that exists will be included.  If
+`ignore missing` is given, it will fall back to rendering nothing if
+none of the templates exist, otherwise it will raise an exception.
+
+Example::
+
+    {% include ['page_detailed.html', 'page.html'] %}
+    {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
+
+.. versionchanged:: 2.4
+   If a template object was passed to the template context you can
+   include that object using `include`.
+
 .. _import:
 
 Import
@@ -713,6 +847,13 @@ namespace::
     </dl>
     <p>{{ textarea('comment') }}</p>
 
+Macros and variables starting with one ore 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:
 
@@ -732,6 +873,20 @@ Here 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:
 
@@ -785,23 +940,31 @@ for Python objects such as strings and numbers.  The following literals exist:
     filter.
 
 true / false:
-    true is always true and false is always false.  Keep in mind that those
-    literals are lowercase!
+    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, when writing `True` expands
+    to an undefined variable that is considered false, all three of them can
+    be written in title case too (`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:
+but exists for completeness' sake.  The following operators are supported:
 
 \+
-    Adds two objects with each other.  Usually numbers but if both objects are
+    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 at the ``~`` operator.  ``{{ 1 + 1 }}`` is ``2``.
 
 \-
-    Substract two numbers from each other.  ``{{ 3 - 2 }}`` is ``1``.
+    Substract the second number from the first one.  ``{{ 3 - 2 }}`` is ``1``.
 
 /
     Divide two numbers.  The return value will be a floating point number.
@@ -809,26 +972,46 @@ but exists for completeness sake.  The following operators are supported:
 
 //
     Divide two numbers and return the truncated integer result.
-    ``{{ 20 / 7 }}`` is ``2``.
+    ``{{ 20 // 7 }}`` is ``2``.
 
 %
-    Calculate the remainder of an integer division between the left and right
-    operand.  ``{{ 11 % 7 }}`` is ``4``.
+    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 string multiple times.
+    return ``4``.  This can also be used to repeat 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 or `if` expressions it can be useful to
-combine group multiple expressions:
+For `if` statements, `for` filtering or `if` expressions it can be useful to
+combine multiple expressions:
 
 and
     Return true if the left and the right operand is true.
@@ -842,12 +1025,12 @@ not
 (expr)
     group an expression.
 
-Note that there is no support for any bit operations or something similar.
+.. admonition:: Note
 
--   special note regarding ``not``: 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).``
+    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
@@ -874,7 +1057,7 @@ is
 
 ()
     Call a callable: ``{{ post.render() }}``.  Inside of the parentheses you
-    can use arguments and keyword arguments like in python:
+    can use positional arguments and keyword arguments like in python:
     ``{{ post.render(user, full=true) }}``.
 
 . / []
@@ -895,6 +1078,11 @@ variable is defined, otherwise from the default layout template::
 The general syntax is ``<do something> if <something is true> else <do
 something else>``.
 
+The `else` part is optional.  If not provided the else block implicitly
+evaluates into an undefined object::
+
+    {{ '[%s]' % page.title if page.title }}
+
 
 .. _builtin-filters:
 
@@ -911,6 +1099,7 @@ List of Builtin Tests
 
 .. jinjatests::
 
+.. _builtin-globals:
 
 List of Global Functions
 ------------------------
@@ -950,6 +1139,64 @@ The following functions are available in the global scope by default:
     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` however you can use this cycler outside of
+    loops or over multiple loops.
+
+    This is for example 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') %}
+        <ul class="browser">
+        {% for folder in folders %}
+          <li class="folder {{ row_class.next() }}">{{ folder|e }}</li>
+        {% endfor %}
+        {% for filename in files %}
+          <li class="file {{ row_class.next() }}">{{ filename|e }}</li>
+        {% endfor %}
+        </ul>
+
+    A cycler has the following attributes and methods:
+
+    .. method:: reset()
+
+        Resets the cycle to the first item.
+
+    .. method:: next()
+
+        Goes one item a head and returns the then current item.
+
+    .. attribute:: current
+
+        Returns the current item.
+
+    **new in Jinja 2.1**
+
+.. class:: joiner(sep=', ')
+
+    A tiny helper that can be use 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 situation 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() }}
+            <a href="?action=edit">Edit</a>
+        {% endif %}
+
+    **new in Jinja 2.1**
+
 
 Extensions
 ----------
@@ -1014,8 +1261,106 @@ For example you can print a translated string easily this way::
 To use placeholders you can use the `format` filter::
 
     {{ _('Hello %(user)s!')|format(user=user.username) }}
-        or
-    {{ _('Hello %s')|format(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 `num` parameter additionally 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 (``{{ ... }}``) just
+that 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 a loop that skips every second item::
+
+    {% for user in users %}
+        {%- if loop.index is even %}{% continue %}{% endif %}
+        ...
+    {% endfor %}
+
+Likewise a look that stops processing after the 10th iteration::
+
+    {% for user in users %}
+        {%- if loop.index >= 10 %}{% break %}{% endif %}
+    {%- endfor %}
+
+
+With Statement
+~~~~~~~~~~~~~~
+
+.. versionadded:: 2.3
+
+If the application enables the :ref:`with-extension` it is possible to
+use the `with` keyword in templates.  This 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 %}
+
+.. _autoescape-overrides:
+
+Autoescape Extension
+--------------------
+
+.. versionadded:: 2.4
+
+If the application enables the :ref:`autoescape-extension` one 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 the `endautoescape` the behavior is reverted to what it was before.