doc/templates.rst
fd0646e4
 Twig for Template Designers
 ===========================
 
 This document describes the syntax and semantics of the template engine and
 will be most useful as reference to those creating Twig templates.
 
 Synopsis
 --------
 
 A template is simply a text file. It can generate any text-based format (HTML,
a855b189
 XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
 ``.xml`` are just fine.
fd0646e4
 
 A template contains **variables** or **expressions**, which get replaced with
b096e21d
 values when the template is evaluated, and **tags**, which control the logic
 of the template.
fd0646e4
 
e2f0b2e2
 Below is a minimal template that illustrates a few basics. We will cover further
b096e21d
 details later on:
 
 .. code-block:: html+jinja
 
     <!DOCTYPE html>
     <html>
         <head>
             <title>My Webpage</title>
         </head>
         <body>
             <ul id="navigation">
             {% for item in navigation %}
                 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
             {% endfor %}
             </ul>
 
             <h1>My Webpage</h1>
             {{ a_variable }}
         </body>
fd0646e4
     </html>
 
a855b189
 There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
 one is used to execute statements such as for-loops, the latter prints the
 result of an expression to the template.
fd0646e4
 
eee3bc28
 IDEs Integration
 ----------------
 
46a8d8d1
 Many IDEs support syntax highlighting and auto-completion for Twig:
eee3bc28
 
46a8d8d1
 * *Textmate* via the `Twig bundle`_
d8346d49
 * *Vim* via the `Jinja syntax plugin`_ or the `vim-twig plugin`_
682b0aa8
 * *Netbeans* via the `Twig syntax plugin`_ (until 7.1, native as of 7.2)
46a8d8d1
 * *PhpStorm* (native as of 2.1)
 * *Eclipse* via the `Twig plugin`_
d03edac8
 * *Sublime Text* via the `Twig bundle`_
e6dde1d6
 * *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects)
95b97eb8
 * *Coda* and *SubEthaEdit* via the `Twig syntax mode`_
12dff669
 * *Coda 2* via the `other Twig syntax mode`_
fce92f84
 * *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode
ca3b1566
 * *Notepad++* via the `Notepad++ Twig Highlighter`_
6c01c14f
 * *Emacs* via `web-mode.el`_
c90d4698
 * *Atom* via the `PHP-twig for atom`_
eee3bc28
 
fd0646e4
 Variables
 ---------
 
e2f0b2e2
 The application passes variables to the templates for manipulation in the
 template. Variables may have attributes or elements you can access,
 too. The visual representation of a variable depends heavily on the application providing
 it.
fd0646e4
 
b096e21d
 You can use a dot (``.``) to access attributes of a variable (methods or
 properties of a PHP object, or items of a PHP array), or the so-called
 "subscript" syntax (``[]``):
fd0646e4
 
a855b189
 .. code-block:: jinja
 
fd0646e4
     {{ foo.bar }}
     {{ foo['bar'] }}
 
d70860f5
 When the attribute contains special characters (like ``-`` that would be
 interpreted as the minus operator), use the ``attribute`` function instead to
 access the variable attribute:
 
 .. code-block:: jinja
 
     {# equivalent to the non-working foo.data-foo #}
     {{ attribute(foo, 'data-foo') }}
 
a855b189
 .. note::
 
     It's important to know that the curly braces are *not* part of the
e2f0b2e2
     variable but the print statement. When accessing variables inside tags,
     don't put the braces around them.
a855b189
 
e2f0b2e2
 If a variable or attribute does not exist, you will receive a ``null`` value
7f00cb9d
 when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
e2f0b2e2
 is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
a855b189
 
 .. sidebar:: Implementation
 
e2f0b2e2
     For convenience's sake ``foo.bar`` does the following things on the PHP
b096e21d
     layer:
a855b189
 
b096e21d
     * check if ``foo`` is an array and ``bar`` a valid element;
     * if not, and if ``foo`` is an object, check that ``bar`` is a valid property;
     * if not, and if ``foo`` is an object, check that ``bar`` is a valid method
       (even if ``bar`` is the constructor - use ``__construct()`` instead);
     * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method;
     * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
     * if not, return a ``null`` value.
a855b189
 
b096e21d
     ``foo['bar']`` on the other hand only works with PHP arrays:
a855b189
 
b096e21d
     * check if ``foo`` is an array and ``bar`` a valid element;
     * if not, return a ``null`` value.
fd0646e4
 
c609060f
 .. note::
 
e2f0b2e2
     If you want to access a dynamic attribute of a variable, use the
b096e21d
     :doc:`attribute<functions/attribute>` function instead.
 
 Global Variables
 ~~~~~~~~~~~~~~~~
c609060f
 
b096e21d
 The following variables are always available in templates:
80af3153
 
5514c8ee
 * ``_self``: references the current template (deprecated since Twig 1.20);
a855b189
 * ``_context``: references the current context;
3cbcc1f4
 * ``_charset``: references the current charset.
80af3153
 
b096e21d
 Setting Variables
 ~~~~~~~~~~~~~~~~~
 
 You can assign values to variables inside code blocks. Assignments use the
 :doc:`set<tags/set>` tag:
 
 .. code-block:: jinja
 
     {% set foo = 'foo' %}
     {% set foo = [1, 2] %}
     {% set foo = {'foo': 'bar'} %}
 
fd0646e4
 Filters
 -------
 
0ef1cb0c
 Variables can be modified by **filters**. Filters are separated from the
a855b189
 variable by a pipe symbol (``|``) and may have optional arguments in
fd0646e4
 parentheses. Multiple filters can be chained. The output of one filter is
 applied to the next.
 
b096e21d
 The following example removes all HTML tags from the ``name`` and title-cases
 it:
fd0646e4
 
b096e21d
 .. code-block:: jinja
5d6e7e2e
 
b096e21d
     {{ name|striptags|title }}
fd0646e4
 
b096e21d
 Filters that accept arguments have parentheses around the arguments. This
 example will join a list by commas:
fd0646e4
 
a855b189
 .. code-block:: jinja
 
b096e21d
     {{ list|join(', ') }}
fd0646e4
 
e2f0b2e2
 To apply a filter on a section of code, wrap it in the
b096e21d
 :doc:`filter<tags/filter>` tag:
fd0646e4
 
b096e21d
 .. code-block:: jinja
91750f37
 
b096e21d
     {% filter upper %}
25e7befa
         This text becomes uppercase
b096e21d
     {% endfilter %}
 
e2f0b2e2
 Go to the :doc:`filters<filters/index>` page to learn more about built-in
b096e21d
 filters.
fd0646e4
 
b096e21d
 Functions
 ---------
 
 Functions can be called to generate content. Functions are called by their
 name followed by parentheses (``()``) and may have arguments.
 
 For instance, the ``range`` function returns a list containing an arithmetic
 progression of integers:
a855b189
 
 .. code-block:: jinja
1d2afa09
 
b096e21d
     {% for i in range(0, 3) %}
         {{ i }},
     {% endfor %}
1d2afa09
 
b096e21d
 Go to the :doc:`functions<functions/index>` page to learn more about the
 built-in functions.
1d2afa09
 
a59dcde3
 Named Arguments
 ---------------
 
 .. versionadded:: 1.12
     Support for named arguments was added in Twig 1.12.
 
 .. code-block:: jinja
 
     {% for i in range(low=1, high=10, step=2) %}
         {{ i }},
     {% endfor %}
 
 Using named arguments makes your templates more explicit about the meaning of
 the values you pass as arguments:
 
 .. code-block:: jinja
 
     {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
 
     {# versus #}
 
     {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
 
 Named arguments also allow you to skip some arguments for which you don't want
9d25425d
 to change the default value:
a59dcde3
 
 .. code-block:: jinja
 
     {# the first argument is the date format, which defaults to the global date format if null is passed #}
     {{ "now"|date(null, "Europe/Paris") }}
 
e2f0b2e2
     {# or skip the format value by using a named argument for the time zone #}
a59dcde3
     {{ "now"|date(timezone="Europe/Paris") }}
 
135b618f
 You can also use both positional and named arguments in one call, in which
 case positional arguments must always come before named arguments:
a59dcde3
 
 .. code-block:: jinja
 
     {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
 
 .. tip::
 
     Each function and filter documentation page has a section where the names
     of all arguments are listed when supported.
 
b096e21d
 Control Structure
 -----------------
8f158bdd
 
b096e21d
 A control structure refers to all those things that control the flow of a
 program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as
 well as things like blocks. Control structures appear inside ``{% ... %}``
 blocks.
8f158bdd
 
b096e21d
 For example, to display a list of users provided in a variable called
 ``users``, use the :doc:`for<tags/for>` tag:
8f158bdd
 
b096e21d
 .. code-block:: jinja
485213a2
 
b096e21d
     <h1>Members</h1>
     <ul>
         {% for user in users %}
             <li>{{ user.username|e }}</li>
         {% endfor %}
     </ul>
 
 The :doc:`if<tags/if>` tag can be used to test an expression:
485213a2
 
 .. code-block:: jinja
 
b096e21d
     {% if users|length > 0 %}
         <ul>
             {% for user in users %}
                 <li>{{ user.username|e }}</li>
             {% endfor %}
         </ul>
     {% endif %}
485213a2
 
b096e21d
 Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags.
8f158bdd
 
b096e21d
 Comments
fd0646e4
 --------
 
b096e21d
 To comment-out part of a line in a template, use the comment syntax ``{# ...
 #}``. This is useful for debugging or to add information for other template
 designers or yourself:
fd0646e4
 
b096e21d
 .. code-block:: jinja
 
     {# note: disabled template because we no longer use this
         {% for user in users %}
             ...
         {% endfor %}
     #}
 
 Including other Templates
 -------------------------
 
 The :doc:`include<tags/include>` tag is useful to include a template and
 return the rendered content of that template into the current one:
fd0646e4
 
a855b189
 .. code-block:: jinja
 
b096e21d
     {% include 'sidebar.html' %}
 
 Per default included templates are passed the current context.
 
 The context that is passed to the included template includes variables defined
 in the template:
 
 .. code-block:: jinja
 
     {% for box in boxes %}
         {% include "render_box.html" %}
     {% endfor %}
 
 The included template ``render_box.html`` is able to access ``box``.
fd0646e4
 
b096e21d
 The filename of the template depends on the template loader. For instance, the
 ``Twig_Loader_Filesystem`` allows you to access other templates by giving the
 filename. You can access templates in subdirectories with a slash:
fd0646e4
 
a855b189
 .. code-block:: jinja
 
b096e21d
     {% include "sections/articles/sidebar.html" %}
 
 This behavior depends on the application embedding Twig.
fd0646e4
 
 Template Inheritance
 --------------------
 
 The most powerful part of Twig is template inheritance. Template inheritance
 allows you to build a base "skeleton" template that contains all the common
 elements of your site and defines **blocks** that child templates can
 override.
 
e278aeed
 Sounds complicated but it is very basic. It's easier to understand it by
fd0646e4
 starting with an example.
 
b096e21d
 Let's define a base template, ``base.html``, which defines a simple HTML
4618d753
 skeleton document that you might use for a simple two-column page:
b096e21d
 
 .. code-block:: html+jinja
 
     <!DOCTYPE html>
     <html>
         <head>
             {% block head %}
                 <link rel="stylesheet" href="style.css" />
                 <title>{% block title %}{% endblock %} - My Webpage</title>
             {% endblock %}
         </head>
         <body>
             <div id="content">{% block content %}{% endblock %}</div>
             <div id="footer">
                 {% block footer %}
                     &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
                 {% endblock %}
             </div>
         </body>
336c7b11
     </html>
fd0646e4
 
a61d4208
 In this example, the :doc:`block<tags/block>` tags define four blocks that
 child templates can fill in. All the ``block`` tag does is to tell the
b096e21d
 template engine that a child template may override those portions of the
 template.
fd0646e4
 
 A child template might look like this:
 
a855b189
 .. code-block:: jinja
 
fd0646e4
     {% extends "base.html" %}
 
     {% block title %}Index{% endblock %}
     {% block head %}
b096e21d
         {{ parent() }}
         <style type="text/css">
             .important { color: #336699; }
         </style>
fd0646e4
     {% endblock %}
     {% block content %}
b096e21d
         <h1>Index</h1>
         <p class="important">
4e4d41b0
             Welcome to my awesome homepage.
b096e21d
         </p>
fd0646e4
     {% endblock %}
 
a61d4208
 The :doc:`extends<tags/extends>` tag is the key here. It tells the template
 engine that this template "extends" another template. When the template system
 evaluates this template, first it locates the parent. The extends tag should
 be the first tag in the template.
fd0646e4
 
b096e21d
 Note that since the child template doesn't define the ``footer`` block, the
 value from the parent template is used instead.
fd0646e4
 
b096e21d
 It's possible to render the contents of the parent block by using the
 :doc:`parent<functions/parent>` function. This gives back the results of the
 parent block:
fd0646e4
 
a855b189
 .. code-block:: jinja
 
fd0646e4
     {% block sidebar %}
b096e21d
         <h3>Table Of Contents</h3>
         ...
         {{ parent() }}
e850d979
     {% endblock %}
 
b096e21d
 .. tip::
fd0646e4
 
b096e21d
     The documentation page for the :doc:`extends<tags/extends>` tag describes
     more advanced features like block nesting, scope, dynamic inheritance, and
     conditional inheritance.
fd0646e4
 
28b9b7ba
 .. note::
 
     Twig also supports multiple inheritance with the so called horizontal reuse
     with the help of the :doc:`use<tags/use>` tag. This is an advanced feature
     hardly ever needed in regular templates.
 
fd0646e4
 HTML Escaping
 -------------
 
 When generating HTML from templates, there's always a risk that a variable
 will include characters that affect the resulting HTML. There are two
 approaches: manually escaping each variable or automatically escaping
 everything by default.
 
6e1f5f7b
 Twig supports both, automatic escaping is enabled by default.
fd0646e4
 
a855b189
 .. note::
 
     Automatic escaping is only supported if the *escaper* extension has been
     enabled (which is the default).
fd0646e4
 
a855b189
 Working with Manual Escaping
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fd0646e4
 
7657c01e
 If manual escaping is enabled, it is **your** responsibility to escape
 variables if needed. What to escape? Any variable you don't trust.
 
 Escaping works by piping the variable through the
 :doc:`escape<filters/escape>` or ``e`` filter:
b096e21d
 
 .. code-block:: jinja
 
     {{ user.username|e }}
7657c01e
 
 By default, the ``escape`` filter uses the ``html`` strategy, but depending on
 the escaping context, you might want to explicitly use any other available
 strategies:
 
8f28e789
 .. code-block:: jinja
 
b096e21d
     {{ user.username|e('js') }}
7657c01e
     {{ user.username|e('css') }}
     {{ user.username|e('url') }}
     {{ user.username|e('html_attr') }}
fd0646e4
 
a855b189
 Working with Automatic Escaping
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fd0646e4
 
 Whether automatic escaping is enabled or not, you can mark a section of a
b096e21d
 template to be escaped or not by using the :doc:`autoescape<tags/autoescape>`
 tag:
a855b189
 
 .. code-block:: jinja
fd0646e4
 
7657c01e
     {% autoescape %}
         Everything will be automatically escaped in this block (using the HTML strategy)
     {% endautoescape %}
 
 By default, auto-escaping uses the ``html`` escaping strategy. If you output
 variables in other contexts, you need to explicitly escape them with the
 appropriate escaping strategy:
 
 .. code-block:: jinja
 
     {% autoescape 'js' %}
         Everything will be automatically escaped in this block (using the JS strategy)
fd0646e4
     {% endautoescape %}
 
b096e21d
 Escaping
 --------
fd0646e4
 
b096e21d
 It is sometimes desirable or even necessary to have Twig ignore parts it would
 otherwise handle as variables or blocks. For example if the default syntax is
 used and you want to use ``{{`` as raw string in the template and not start a
 variable you have to use a trick.
fd0646e4
 
b096e21d
 The easiest way is to output the variable delimiter (``{{``) by using a variable
 expression:
9d4ceb45
 
b096e21d
 .. code-block:: jinja
a855b189
 
b096e21d
     {{ '{{' }}
9d4ceb45
 
cd4ab0fd
 For bigger sections it makes sense to mark a block
 :doc:`verbatim<tags/verbatim>`.
fd0646e4
 
b096e21d
 Macros
 ------
fd0646e4
 
4647913e
 .. versionadded:: 1.12
     Support for default argument values was added in Twig 1.12.
 
b096e21d
 Macros are comparable with functions in regular programming languages. They
b6922682
 are useful to reuse often used HTML fragments to not repeat yourself.
fd0646e4
 
b6922682
 A macro is defined via the :doc:`macro<tags/macro>` tag. Here is a small example
 (subsequently called ``forms.html``) of a macro that renders a form element:
a855b189
 
 .. code-block:: jinja
fd0646e4
 
b096e21d
     {% macro input(name, value, type, size) %}
         <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
     {% endmacro %}
588fb930
 
b6922682
 Macros can be defined in any template, and need to be "imported" via the
 :doc:`import<tags/import>` tag before being used:
87ba224c
 
a855b189
 .. code-block:: jinja
 
b096e21d
     {% import "forms.html" as forms %}
a855b189
 
b096e21d
     <p>{{ forms.input('username') }}</p>
2ab4dd5b
 
b6922682
 Alternatively, you can import individual macro names from a template into the
 current namespace via the :doc:`from<tags/from>` tag and optionally alias them:
a855b189
 
 .. code-block:: jinja
2ab4dd5b
 
b6922682
     {% from 'forms.html' import input as input_field %}
a855b189
 
b096e21d
     <dl>
         <dt>Username</dt>
         <dd>{{ input_field('username') }}</dd>
         <dt>Password</dt>
93c4406f
         <dd>{{ input_field('password', '', 'password') }}</dd>
b096e21d
     </dl>
2ab4dd5b
 
4647913e
 A default value can also be defined for macro arguments when not provided in a
 macro call:
 
 .. code-block:: jinja
 
     {% macro input(name, value = "", type = "text", size = 20) %}
         <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
     {% endmacro %}
 
056bb5da
 If extra positional arguments are passed to a macro call, they end up in the
 special ``varargs`` variable as a list of values.
7f00cb9d
 
b7abf4d5
 .. _twig-expressions:
 
b096e21d
 Expressions
 -----------
a855b189
 
b096e21d
 Twig allows expressions everywhere. These work very similar to regular PHP and
 even if you're not working with PHP you should feel comfortable with it.
fd0646e4
 
a855b189
 .. note::
fd0646e4
 
b096e21d
     The operator precedence is as follows, with the lowest-precedence
1dc3c4be
     operators listed first: ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``,
b66181d1
     ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``matches``,
     ``starts with``, ``ends with``, ``..``, ``+``, ``-``, ``~``, ``*``, ``/``,
     ``//``, ``%``, ``is``, ``**``, ``|``, ``[]``, and ``.``:
2acd63ae
 
     .. code-block:: jinja
 
d6e03576
         {% set greeting = 'Hello ' %}
2acd63ae
         {% set name = 'Fabien' %}
 
         {{ greeting ~ name|lower }}   {# Hello fabien #}
 
         {# use parenthesis to change precedence #}
         {{ (greeting ~ name)|lower }} {# hello fabien #}
d47902c7
 
b096e21d
 Literals
 ~~~~~~~~
46eccb9a
 
f3de043d
 .. versionadded:: 1.5
     Support for hash keys as names and expressions was added in Twig 1.5.
 
b096e21d
 The simplest form of expressions are literals. Literals are representations
 for PHP types such as strings, numbers, and arrays. The following literals
 exist:
46eccb9a
 
b096e21d
 * ``"Hello World"``: Everything between two double or single quotes is a
   string. They are useful whenever you need a string in the template (for
8b569e49
   example as arguments to function calls, filters or just to extend or include
   a template). A string can contain a delimiter if it is preceded by a
   backslash (``\``) -- like in ``'It\'s good'``.
fd0646e4
 
a855b189
 * ``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.
fd0646e4
 
3cbcc1f4
 * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
   separated by a comma (``,``) and wrapped with squared brackets (``[]``).
4505200d
 
3cbcc1f4
 * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
f3de043d
   separated by a comma (``,``) and wrapped with curly braces (``{}``):
 
a9aeea41
   .. code-block:: jinja
f3de043d
 
5ee53cd5
     {# keys as string #}
f3de043d
     { 'foo': 'foo', 'bar': 'bar' }
 
5ee53cd5
     {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
f3de043d
     { foo: 'foo', bar: 'bar' }
 
5ee53cd5
     {# keys as integer #}
f3de043d
     { 2: 'foo', 4: 'bar' }
 
5ee53cd5
     {# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
f3de043d
     { (1 + 1): 'foo', (a ~ 'b'): 'bar' }
7b003e86
 
a855b189
 * ``true`` / ``false``: ``true`` represents the true value, ``false``
   represents the false value.
7b3b8930
 
8d00b42e
 * ``null``: ``null`` represents no specific value. This is the value returned
   when a variable does not exist. ``none`` is an alias for ``null``.
7b3b8930
 
4505200d
 Arrays and hashes can be nested:
 
a855b189
 .. code-block:: jinja
 
4505200d
     {% set foo = [1, {"foo": "bar"}] %}
c9eca350
 
459720ff
 .. tip::
 
     Using double-quoted or single-quoted strings has no impact on performance
     but string interpolation is only supported in double-quoted strings.
 
a855b189
 Math
 ~~~~
fd0646e4
 
 Twig allows you to calculate with values. This is rarely useful in templates
 but exists for completeness' sake. The following operators are supported:
 
a855b189
 * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
   1 + 1 }}`` is ``2``.
fd0646e4
 
2c1be8f0
 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
a855b189
   ``1``.
fd0646e4
 
80a2a7ea
 * ``/``: Divides two numbers. The returned value will be a floating point
a855b189
   number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
fd0646e4
 
a855b189
 * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
   ``4``.
fd0646e4
 
a360bc03
 * ``//``: Divides two numbers and returns the floored integer result. ``{{ 20
d8ea1b17
   // 7 }}`` is ``2``, ``{{ -20  // 7 }}`` is ``-3`` (this is just syntactic
a360bc03
   sugar for the :doc:`round<filters/round>` filter).
4af896b9
 
a855b189
 * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
   return ``4``.
fd0646e4
 
bdcb176c
 * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
   3 }}`` would return ``8``.
fd0646e4
 
a855b189
 Logic
 ~~~~~
fd0646e4
 
b096e21d
 You can combine multiple expressions with the following operators:
fd0646e4
 
a855b189
 * ``and``: Returns true if the left and the right operands are both true.
 
 * ``or``: Returns true if the left or the right operand is true.
fd0646e4
 
a855b189
 * ``not``: Negates a statement.
fd0646e4
 
a855b189
 * ``(expr)``: Groups an expression.
fd0646e4
 
1dc3c4be
 .. note::
 
     Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
 
29986a9c
 .. note::
 
     Operators are case sensitive.
 
a855b189
 Comparisons
 ~~~~~~~~~~~
fd0646e4
 
a855b189
 The following comparison operators are supported in any expression: ``==``,
 ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
fd0646e4
 
b66181d1
 You can also check if a string ``starts with`` or ``ends with`` another
 string:
 
 .. code-block:: jinja
 
     {% if 'Fabien' starts with 'F' %}
     {% endif %}
 
     {% if 'Fabien' ends with 'n' %}
     {% endif %}
 
 .. note::
 
     For complex string comparisons, the ``matches`` operator allows you to use
     `regular expressions`_:
 
     .. code-block:: jinja
 
33dcbc8c
         {% if phone matches '/^[\\d\\.]+$/' %}
b66181d1
         {% endif %}
 
3cbcc1f4
 Containment Operator
 ~~~~~~~~~~~~~~~~~~~~
fd0646e4
 
a855b189
 The ``in`` operator performs containment test.
49799bc3
 
a855b189
 It returns ``true`` if the left operand is contained in the right:
49799bc3
 
a855b189
 .. code-block:: jinja
49799bc3
 
     {# returns true #}
 
     {{ 1 in [1, 2, 3] }}
 
     {{ 'cd' in 'abcde' }}
 
 .. tip::
 
     You can use this filter to perform a containment test on strings, arrays,
a855b189
     or objects implementing the ``Traversable`` interface.
49799bc3
 
a855b189
 To perform a negative test, use the ``not in`` operator:
 
 .. code-block:: jinja
49799bc3
 
     {% if 1 not in [1, 2, 3] %}
 
     {# is equivalent to #}
     {% if not (1 in [1, 2, 3]) %}
 
b096e21d
 Test Operator
 ~~~~~~~~~~~~~
49799bc3
 
a855b189
 The ``is`` operator performs tests. Tests can be used to test a variable against
49799bc3
 a common expression. The right operand is name of the test:
 
a855b189
 .. code-block:: jinja
 
49799bc3
     {# find out if a variable is odd #}
 
     {{ name is odd }}
 
 Tests can accept arguments too:
 
a855b189
 .. code-block:: jinja
 
52c952c1
     {% if post.status is constant('Post::PUBLISHED') %}
49799bc3
 
904dfefb
 Tests can be negated by using the ``is not`` operator:
a855b189
 
 .. code-block:: jinja
49799bc3
 
f9013d55
     {% if post.status is not constant('Post::PUBLISHED') %}
49799bc3
 
     {# is equivalent to #}
52c952c1
     {% if not (post.status is constant('Post::PUBLISHED')) %}
49799bc3
 
b096e21d
 Go to the :doc:`tests<tests/index>` page to learn more about the built-in
 tests.
49799bc3
 
a855b189
 Other Operators
 ~~~~~~~~~~~~~~~
fd0646e4
 
45850f55
 .. versionadded:: 1.12.0
     Support for the extended ternary operator was added in Twig 1.12.0.
f85076b0
 
fd0646e4
 The following operators are very useful but don't fit into any of the other
b096e21d
 categories:
fd0646e4
 
3cbcc1f4
 * ``..``: Creates a sequence based on the operand before and after the
b096e21d
   operator (this is just syntactic sugar for the :doc:`range<functions/range>`
   function).
a855b189
 
 * ``|``: Applies a filter.
2ab4dd5b
 
a855b189
 * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
   " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
   John!``.
fd0646e4
 
a855b189
 * ``.``, ``[]``: Gets an attribute of an object.
fd0646e4
 
f85076b0
 * ``?:``: The ternary operator:
 
   .. code-block:: jinja
 
       {{ foo ? 'yes' : 'no' }}
 
45850f55
       {# as of Twig 1.12.0 #}
b66181d1
       {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
       {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
fd0646e4
 
6e2d7ba1
 String Interpolation
 ~~~~~~~~~~~~~~~~~~~~
 
 .. versionadded:: 1.5
     String interpolation was added in Twig 1.5.
 
 String interpolation (`#{expression}`) allows any valid expression to appear
459720ff
 within a *double-quoted string*. The result of evaluating that expression is
 inserted into the string:
6e2d7ba1
 
 .. code-block:: jinja
 
     {{ "foo #{bar} baz" }}
     {{ "foo #{1 + 2} baz" }}
 
df9da8e8
 .. _templates-whitespace-control:
 
b096e21d
 Whitespace Control
 ------------------
fd0646e4
 
8a5f6bf6
 .. versionadded:: 1.1
b096e21d
     Tag level whitespace control was added in Twig 1.1.
 
 The first newline after a template tag is removed automatically (like in PHP.)
 Whitespace is not further modified by the template engine, so each whitespace
 (spaces, tabs, newlines etc.) is returned unchanged.
8a5f6bf6
 
b096e21d
 Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
a855b189
 
 .. code-block:: jinja
fd0646e4
 
b096e21d
     {% spaceless %}
         <div>
2861befc
             <strong>foo bar</strong>
b096e21d
         </div>
     {% endspaceless %}
b1b173f1
 
2861befc
     {# output will be <div><strong>foo bar</strong></div> #}
47a73476
 
b096e21d
 In addition to the spaceless tag you can also control whitespace on a per tag
 level. By using the whitespace control modifier on your tags, you can trim
 leading and or trailing whitespace:
47a73476
 
 .. code-block:: jinja
 
b096e21d
     {% set value = 'no spaces' %}
     {#- No leading/trailing whitespace -#}
     {%- if true -%}
         {{- value -}}
     {%- endif -%}
c609060f
 
b096e21d
     {# output 'no spaces' #}
c609060f
 
b096e21d
 The above sample shows the default whitespace control modifier, and how you can
 use it to remove whitespace around tags.  Trimming space will consume all whitespace
 for that side of the tag.  It is possible to use whitespace trimming on one side
 of a tag:
c609060f
 
 .. code-block:: jinja
 
b096e21d
     {% set value = 'no spaces' %}
     <li>    {{- value }}    </li>
c609060f
 
b096e21d
     {# outputs '<li>no spaces    </li>' #}
c609060f
 
522001fd
 Extensions
 ----------
 
b096e21d
 Twig can be easily extended.
5ea7020a
 
b096e21d
 If you are looking for new tags, filters, or functions, have a look at the Twig official
 `extension repository`_.
5ea7020a
 
5923f0cb
 If you want to create your own, read the :ref:`Creating an
 Extension<creating_extensions>` chapter.
5ea7020a
 
37e7ba75
 .. _`Twig bundle`:                https://github.com/Anomareh/PHP-Twig.tmbundle
d8346d49
 .. _`Jinja syntax plugin`:        http://jinja.pocoo.org/docs/integration/#vim
 .. _`vim-twig plugin`:            https://github.com/evidens/vim-twig
37e7ba75
 .. _`Twig syntax plugin`:         http://plugins.netbeans.org/plugin/37069/php-twig
 .. _`Twig plugin`:                https://github.com/pulse00/Twig-Eclipse-Plugin
 .. _`Twig language definition`:   https://github.com/gabrielcorpse/gedit-twig-template-language
e37fc6b0
 .. _`extension repository`:       http://github.com/twigphp/Twig-extensions
37e7ba75
 .. _`Twig syntax mode`:           https://github.com/bobthecow/Twig-HTML.mode
 .. _`other Twig syntax mode`:     https://github.com/muxx/Twig-HTML.mode
 .. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig
6c01c14f
 .. _`web-mode.el`:                http://web-mode.org/
b66181d1
 .. _`regular expressions`:        http://php.net/manual/en/pcre.pattern.php
c90d4698
 .. _`PHP-twig for atom`:          https://github.com/reesef/php-twig