1Twig for Template Designers
2===========================
3
4This document describes the syntax and semantics of the template engine and
5will be most useful as reference to those creating Twig templates.
6
7Synopsis
8--------
9
10A template is simply a text file. It can generate any text-based format (HTML,
11XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
12``.xml`` are just fine.
13
14A template contains **variables** or **expressions**, which get replaced with
15values when the template is evaluated, and **tags**, which control the logic
16of the template.
17
18Below is a minimal template that illustrates a few basics. We will cover further
19details later on:
20
21.. code-block:: html+jinja
22
23    <!DOCTYPE html>
24    <html>
25        <head>
26            <title>My Webpage</title>
27        </head>
28        <body>
29            <ul id="navigation">
30            {% for item in navigation %}
31                <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
32            {% endfor %}
33            </ul>
34
35            <h1>My Webpage</h1>
36            {{ a_variable }}
37        </body>
38    </html>
39
40There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
41one is used to execute statements such as for-loops, the latter prints the
42result of an expression to the template.
43
44IDEs Integration
45----------------
46
47Many IDEs support syntax highlighting and auto-completion for Twig:
48
49* *Textmate* via the `Twig bundle`_
50* *Vim* via the `Jinja syntax plugin`_ or the `vim-twig plugin`_
51* *Netbeans* via the `Twig syntax plugin`_ (until 7.1, native as of 7.2)
52* *PhpStorm* (native as of 2.1)
53* *Eclipse* via the `Twig plugin`_
54* *Sublime Text* via the `Twig bundle`_
55* *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects)
56* *Coda* and *SubEthaEdit* via the `Twig syntax mode`_
57* *Coda 2* via the `other Twig syntax mode`_
58* *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode
59* *Notepad++* via the `Notepad++ Twig Highlighter`_
60* *Emacs* via `web-mode.el`_
61* *Atom* via the `PHP-twig for atom`_
62* *Visual Studio Code* via the `Twig pack`_
63
64Also, `TwigFiddle`_ is an online service that allows you to execute Twig templates
65from a browser; it supports all versions of Twig.
66
67Variables
68---------
69
70The application passes variables to the templates for manipulation in the
71template. Variables may have attributes or elements you can access,
72too. The visual representation of a variable depends heavily on the application providing
73it.
74
75You can use a dot (``.``) to access attributes of a variable (methods or
76properties of a PHP object, or items of a PHP array), or the so-called
77"subscript" syntax (``[]``):
78
79.. code-block:: jinja
80
81    {{ foo.bar }}
82    {{ foo['bar'] }}
83
84When the attribute contains special characters (like ``-`` that would be
85interpreted as the minus operator), use the ``attribute`` function instead to
86access the variable attribute:
87
88.. code-block:: jinja
89
90    {# equivalent to the non-working foo.data-foo #}
91    {{ attribute(foo, 'data-foo') }}
92
93.. note::
94
95    It's important to know that the curly braces are *not* part of the
96    variable but the print statement. When accessing variables inside tags,
97    don't put the braces around them.
98
99If a variable or attribute does not exist, you will receive a ``null`` value
100when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
101is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
102
103.. sidebar:: Implementation
104
105    For convenience's sake ``foo.bar`` does the following things on the PHP
106    layer:
107
108    * check if ``foo`` is an array and ``bar`` a valid element;
109    * if not, and if ``foo`` is an object, check that ``bar`` is a valid property;
110    * if not, and if ``foo`` is an object, check that ``bar`` is a valid method
111      (even if ``bar`` is the constructor - use ``__construct()`` instead);
112    * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method;
113    * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
114    * if not, return a ``null`` value.
115
116    ``foo['bar']`` on the other hand only works with PHP arrays:
117
118    * check if ``foo`` is an array and ``bar`` a valid element;
119    * if not, return a ``null`` value.
120
121.. note::
122
123    If you want to access a dynamic attribute of a variable, use the
124    :doc:`attribute<functions/attribute>` function instead.
125
126Global Variables
127~~~~~~~~~~~~~~~~
128
129The following variables are always available in templates:
130
131* ``_self``: references the current template;
132* ``_context``: references the current context;
133* ``_charset``: references the current charset.
134
135Setting Variables
136~~~~~~~~~~~~~~~~~
137
138You can assign values to variables inside code blocks. Assignments use the
139:doc:`set<tags/set>` tag:
140
141.. code-block:: jinja
142
143    {% set foo = 'foo' %}
144    {% set foo = [1, 2] %}
145    {% set foo = {'foo': 'bar'} %}
146
147Filters
148-------
149
150Variables can be modified by **filters**. Filters are separated from the
151variable by a pipe symbol (``|``) and may have optional arguments in
152parentheses. Multiple filters can be chained. The output of one filter is
153applied to the next.
154
155The following example removes all HTML tags from the ``name`` and title-cases
156it:
157
158.. code-block:: jinja
159
160    {{ name|striptags|title }}
161
162Filters that accept arguments have parentheses around the arguments. This
163example will join a list by commas:
164
165.. code-block:: jinja
166
167    {{ list|join(', ') }}
168
169To apply a filter on a section of code, wrap it in the
170:doc:`filter<tags/filter>` tag:
171
172.. code-block:: jinja
173
174    {% filter upper %}
175        This text becomes uppercase
176    {% endfilter %}
177
178Go to the :doc:`filters<filters/index>` page to learn more about built-in
179filters.
180
181Functions
182---------
183
184Functions can be called to generate content. Functions are called by their
185name followed by parentheses (``()``) and may have arguments.
186
187For instance, the ``range`` function returns a list containing an arithmetic
188progression of integers:
189
190.. code-block:: jinja
191
192    {% for i in range(0, 3) %}
193        {{ i }},
194    {% endfor %}
195
196Go to the :doc:`functions<functions/index>` page to learn more about the
197built-in functions.
198
199.. _named-arguments:
200
201Named Arguments
202---------------
203
204.. versionadded:: 1.12
205    Support for named arguments was added in Twig 1.12.
206
207.. code-block:: jinja
208
209    {% for i in range(low=1, high=10, step=2) %}
210        {{ i }},
211    {% endfor %}
212
213Using named arguments makes your templates more explicit about the meaning of
214the values you pass as arguments:
215
216.. code-block:: jinja
217
218    {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
219
220    {# versus #}
221
222    {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
223
224Named arguments also allow you to skip some arguments for which you don't want
225to change the default value:
226
227.. code-block:: jinja
228
229    {# the first argument is the date format, which defaults to the global date format if null is passed #}
230    {{ "now"|date(null, "Europe/Paris") }}
231
232    {# or skip the format value by using a named argument for the time zone #}
233    {{ "now"|date(timezone="Europe/Paris") }}
234
235You can also use both positional and named arguments in one call, in which
236case positional arguments must always come before named arguments:
237
238.. code-block:: jinja
239
240    {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
241
242.. tip::
243
244    Each function and filter documentation page has a section where the names
245    of all arguments are listed when supported.
246
247Control Structure
248-----------------
249
250A control structure refers to all those things that control the flow of a
251program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as
252well as things like blocks. Control structures appear inside ``{% ... %}``
253blocks.
254
255For example, to display a list of users provided in a variable called
256``users``, use the :doc:`for<tags/for>` tag:
257
258.. code-block:: jinja
259
260    <h1>Members</h1>
261    <ul>
262        {% for user in users %}
263            <li>{{ user.username|e }}</li>
264        {% endfor %}
265    </ul>
266
267The :doc:`if<tags/if>` tag can be used to test an expression:
268
269.. code-block:: jinja
270
271    {% if users|length > 0 %}
272        <ul>
273            {% for user in users %}
274                <li>{{ user.username|e }}</li>
275            {% endfor %}
276        </ul>
277    {% endif %}
278
279Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags.
280
281Comments
282--------
283
284To comment-out part of a line in a template, use the comment syntax ``{# ...
285#}``. This is useful for debugging or to add information for other template
286designers or yourself:
287
288.. code-block:: jinja
289
290    {# note: disabled template because we no longer use this
291        {% for user in users %}
292            ...
293        {% endfor %}
294    #}
295
296Including other Templates
297-------------------------
298
299The :doc:`include<functions/include>` function is useful to include a template
300and return the rendered content of that template into the current one:
301
302.. code-block:: jinja
303
304    {{ include('sidebar.html') }}
305
306By default, included templates have access to the same context as the template
307which includes them. This means that any variable defined in the main template
308will be available in the included template too:
309
310.. code-block:: jinja
311
312    {% for box in boxes %}
313        {{ include('render_box.html') }}
314    {% endfor %}
315
316The included template ``render_box.html`` is able to access the ``box`` variable.
317
318The name of the template depends on the template loader. For instance, the
319``\Twig\Loader\FilesystemLoader`` allows you to access other templates by giving the
320filename. You can access templates in subdirectories with a slash:
321
322.. code-block:: jinja
323
324    {{ include('sections/articles/sidebar.html') }}
325
326This behavior depends on the application embedding Twig.
327
328Template Inheritance
329--------------------
330
331The most powerful part of Twig is template inheritance. Template inheritance
332allows you to build a base "skeleton" template that contains all the common
333elements of your site and defines **blocks** that child templates can
334override.
335
336Sounds complicated but it is very basic. It's easier to understand it by
337starting with an example.
338
339Let's define a base template, ``base.html``, which defines a simple HTML
340skeleton document that you might use for a simple two-column page:
341
342.. code-block:: html+jinja
343
344    <!DOCTYPE html>
345    <html>
346        <head>
347            {% block head %}
348                <link rel="stylesheet" href="style.css" />
349                <title>{% block title %}{% endblock %} - My Webpage</title>
350            {% endblock %}
351        </head>
352        <body>
353            <div id="content">{% block content %}{% endblock %}</div>
354            <div id="footer">
355                {% block footer %}
356                    &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
357                {% endblock %}
358            </div>
359        </body>
360    </html>
361
362In this example, the :doc:`block<tags/block>` tags define four blocks that
363child templates can fill in. All the ``block`` tag does is to tell the
364template engine that a child template may override those portions of the
365template.
366
367A child template might look like this:
368
369.. code-block:: jinja
370
371    {% extends "base.html" %}
372
373    {% block title %}Index{% endblock %}
374    {% block head %}
375        {{ parent() }}
376        <style type="text/css">
377            .important { color: #336699; }
378        </style>
379    {% endblock %}
380    {% block content %}
381        <h1>Index</h1>
382        <p class="important">
383            Welcome to my awesome homepage.
384        </p>
385    {% endblock %}
386
387The :doc:`extends<tags/extends>` tag is the key here. It tells the template
388engine that this template "extends" another template. When the template system
389evaluates this template, first it locates the parent. The extends tag should
390be the first tag in the template.
391
392Note that since the child template doesn't define the ``footer`` block, the
393value from the parent template is used instead.
394
395It's possible to render the contents of the parent block by using the
396:doc:`parent<functions/parent>` function. This gives back the results of the
397parent block:
398
399.. code-block:: jinja
400
401    {% block sidebar %}
402        <h3>Table Of Contents</h3>
403        ...
404        {{ parent() }}
405    {% endblock %}
406
407.. tip::
408
409    The documentation page for the :doc:`extends<tags/extends>` tag describes
410    more advanced features like block nesting, scope, dynamic inheritance, and
411    conditional inheritance.
412
413.. note::
414
415    Twig also supports multiple inheritance with the so called horizontal reuse
416    with the help of the :doc:`use<tags/use>` tag. This is an advanced feature
417    hardly ever needed in regular templates.
418
419HTML Escaping
420-------------
421
422When generating HTML from templates, there's always a risk that a variable
423will include characters that affect the resulting HTML. There are two
424approaches: manually escaping each variable or automatically escaping
425everything by default.
426
427Twig supports both, automatic escaping is enabled by default.
428
429The automatic escaping strategy can be configured via the
430:ref:`autoescape<environment_options>` option and defaults to ``html``.
431
432Working with Manual Escaping
433~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434
435If manual escaping is enabled, it is **your** responsibility to escape
436variables if needed. What to escape? Any variable you don't trust.
437
438Escaping works by piping the variable through the
439:doc:`escape<filters/escape>` or ``e`` filter:
440
441.. code-block:: jinja
442
443    {{ user.username|e }}
444
445By default, the ``escape`` filter uses the ``html`` strategy, but depending on
446the escaping context, you might want to explicitly use any other available
447strategies:
448
449.. code-block:: jinja
450
451    {{ user.username|e('js') }}
452    {{ user.username|e('css') }}
453    {{ user.username|e('url') }}
454    {{ user.username|e('html_attr') }}
455
456Working with Automatic Escaping
457~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
458
459Whether automatic escaping is enabled or not, you can mark a section of a
460template to be escaped or not by using the :doc:`autoescape<tags/autoescape>`
461tag:
462
463.. code-block:: jinja
464
465    {% autoescape %}
466        Everything will be automatically escaped in this block (using the HTML strategy)
467    {% endautoescape %}
468
469By default, auto-escaping uses the ``html`` escaping strategy. If you output
470variables in other contexts, you need to explicitly escape them with the
471appropriate escaping strategy:
472
473.. code-block:: jinja
474
475    {% autoescape 'js' %}
476        Everything will be automatically escaped in this block (using the JS strategy)
477    {% endautoescape %}
478
479Escaping
480--------
481
482It is sometimes desirable or even necessary to have Twig ignore parts it would
483otherwise handle as variables or blocks. For example if the default syntax is
484used and you want to use ``{{`` as raw string in the template and not start a
485variable you have to use a trick.
486
487The easiest way is to output the variable delimiter (``{{``) by using a variable
488expression:
489
490.. code-block:: jinja
491
492    {{ '{{' }}
493
494For bigger sections it makes sense to mark a block
495:doc:`verbatim<tags/verbatim>`.
496
497Macros
498------
499
500.. versionadded:: 1.12
501    Support for default argument values was added in Twig 1.12.
502
503Macros are comparable with functions in regular programming languages. They
504are useful to reuse often used HTML fragments to not repeat yourself.
505
506A macro is defined via the :doc:`macro<tags/macro>` tag. Here is a small example
507(subsequently called ``forms.html``) of a macro that renders a form element:
508
509.. code-block:: jinja
510
511    {% macro input(name, value, type, size) %}
512        <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
513    {% endmacro %}
514
515Macros can be defined in any template, and need to be "imported" via the
516:doc:`import<tags/import>` tag before being used:
517
518.. code-block:: jinja
519
520    {% import "forms.html" as forms %}
521
522    <p>{{ forms.input('username') }}</p>
523
524Alternatively, you can import individual macro names from a template into the
525current namespace via the :doc:`from<tags/from>` tag and optionally alias them:
526
527.. code-block:: jinja
528
529    {% from 'forms.html' import input as input_field %}
530
531    <dl>
532        <dt>Username</dt>
533        <dd>{{ input_field('username') }}</dd>
534        <dt>Password</dt>
535        <dd>{{ input_field('password', '', 'password') }}</dd>
536    </dl>
537
538A default value can also be defined for macro arguments when not provided in a
539macro call:
540
541.. code-block:: jinja
542
543    {% macro input(name, value = "", type = "text", size = 20) %}
544        <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
545    {% endmacro %}
546
547If extra positional arguments are passed to a macro call, they end up in the
548special ``varargs`` variable as a list of values.
549
550.. _twig-expressions:
551
552Expressions
553-----------
554
555Twig allows expressions everywhere. These work very similar to regular PHP and
556even if you're not working with PHP you should feel comfortable with it.
557
558.. note::
559
560    The operator precedence is as follows, with the lowest-precedence operators
561    listed first: ``?:`` (ternary operator), ``b-and``, ``b-xor``, ``b-or``,
562    ``or``, ``and``, ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``,
563    ``matches``, ``starts with``, ``ends with``, ``..``, ``+``, ``-``, ``~``,
564    ``*``, ``/``, ``//``, ``%``, ``is`` (tests), ``**``, ``??``, ``|``
565    (filters), ``[]``, and ``.``.
566
567    .. code-block:: jinja
568
569        {% set greeting = 'Hello ' %}
570        {% set name = 'Fabien' %}
571
572        {{ greeting ~ name|lower }}   {# Hello fabien #}
573
574        {# use parenthesis to change precedence #}
575        {{ (greeting ~ name)|lower }} {# hello fabien #}
576
577Literals
578~~~~~~~~
579
580.. versionadded:: 1.5
581    Support for hash keys as names and expressions was added in Twig 1.5.
582
583The simplest form of expressions are literals. Literals are representations
584for PHP types such as strings, numbers, and arrays. The following literals
585exist:
586
587* ``"Hello World"``: Everything between two double or single quotes is a
588  string. They are useful whenever you need a string in the template (for
589  example as arguments to function calls, filters or just to extend or include
590  a template). A string can contain a delimiter if it is preceded by a
591  backslash (``\``) -- like in ``'It\'s good'``. If the string contains a
592  backslash (e.g. ``'c:\Program Files'``) escape it by doubling it
593  (e.g. ``'c:\\Program Files'``).
594
595* ``42`` / ``42.23``: Integers and floating point numbers are created by just
596  writing the number down. If a dot is present the number is a float,
597  otherwise an integer.
598
599* ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
600  separated by a comma (``,``) and wrapped with squared brackets (``[]``).
601
602* ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
603  separated by a comma (``,``) and wrapped with curly braces (``{}``):
604
605  .. code-block:: jinja
606
607    {# keys as string #}
608    { 'foo': 'foo', 'bar': 'bar' }
609
610    {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
611    { foo: 'foo', bar: 'bar' }
612
613    {# keys as integer #}
614    { 2: 'foo', 4: 'bar' }
615
616    {# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
617    {% set foo = 'foo' %}
618    { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
619
620* ``true`` / ``false``: ``true`` represents the true value, ``false``
621  represents the false value.
622
623* ``null``: ``null`` represents no specific value. This is the value returned
624  when a variable does not exist. ``none`` is an alias for ``null``.
625
626Arrays and hashes can be nested:
627
628.. code-block:: jinja
629
630    {% set foo = [1, {"foo": "bar"}] %}
631
632.. tip::
633
634    Using double-quoted or single-quoted strings has no impact on performance
635    but string interpolation is only supported in double-quoted strings.
636
637Math
638~~~~
639
640Twig allows you to calculate with values. This is rarely useful in templates
641but exists for completeness' sake. The following operators are supported:
642
643* ``+``: Adds two objects together (the operands are casted to numbers). ``{{
644  1 + 1 }}`` is ``2``.
645
646* ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
647  ``1``.
648
649* ``/``: Divides two numbers. The returned value will be a floating point
650  number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
651
652* ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
653  ``4``.
654
655* ``//``: Divides two numbers and returns the floored integer result. ``{{ 20
656  // 7 }}`` is ``2``, ``{{ -20  // 7 }}`` is ``-3`` (this is just syntactic
657  sugar for the :doc:`round<filters/round>` filter).
658
659* ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
660  return ``4``.
661
662* ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
663  3 }}`` would return ``8``.
664
665.. _template_logic:
666
667Logic
668~~~~~
669
670You can combine multiple expressions with the following operators:
671
672* ``and``: Returns true if the left and the right operands are both true.
673
674* ``or``: Returns true if the left or the right operand is true.
675
676* ``not``: Negates a statement.
677
678* ``(expr)``: Groups an expression.
679
680.. note::
681
682    Twig also supports bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
683
684.. note::
685
686    Operators are case sensitive.
687
688Comparisons
689~~~~~~~~~~~
690
691The following comparison operators are supported in any expression: ``==``,
692``!=``, ``<``, ``>``, ``>=``, and ``<=``.
693
694You can also check if a string ``starts with`` or ``ends with`` another
695string:
696
697.. code-block:: jinja
698
699    {% if 'Fabien' starts with 'F' %}
700    {% endif %}
701
702    {% if 'Fabien' ends with 'n' %}
703    {% endif %}
704
705.. note::
706
707    For complex string comparisons, the ``matches`` operator allows you to use
708    `regular expressions`_:
709
710    .. code-block:: jinja
711
712        {% if phone matches '/^[\\d\\.]+$/' %}
713        {% endif %}
714
715Containment Operator
716~~~~~~~~~~~~~~~~~~~~
717
718The ``in`` operator performs containment test.
719
720It returns ``true`` if the left operand is contained in the right:
721
722.. code-block:: jinja
723
724    {# returns true #}
725
726    {{ 1 in [1, 2, 3] }}
727
728    {{ 'cd' in 'abcde' }}
729
730.. tip::
731
732    You can use this filter to perform a containment test on strings, arrays,
733    or objects implementing the ``Traversable`` interface.
734
735To perform a negative test, use the ``not in`` operator:
736
737.. code-block:: jinja
738
739    {% if 1 not in [1, 2, 3] %}
740
741    {# is equivalent to #}
742    {% if not (1 in [1, 2, 3]) %}
743
744Test Operator
745~~~~~~~~~~~~~
746
747The ``is`` operator performs tests. Tests can be used to test a variable against
748a common expression. The right operand is name of the test:
749
750.. code-block:: jinja
751
752    {# find out if a variable is odd #}
753
754    {{ name is odd }}
755
756Tests can accept arguments too:
757
758.. code-block:: jinja
759
760    {% if post.status is constant('Post::PUBLISHED') %}
761
762Tests can be negated by using the ``is not`` operator:
763
764.. code-block:: jinja
765
766    {% if post.status is not constant('Post::PUBLISHED') %}
767
768    {# is equivalent to #}
769    {% if not (post.status is constant('Post::PUBLISHED')) %}
770
771Go to the :doc:`tests<tests/index>` page to learn more about the built-in
772tests.
773
774Other Operators
775~~~~~~~~~~~~~~~
776
777.. versionadded:: 1.12.0
778    Support for the extended ternary operator was added in Twig 1.12.0.
779
780The following operators don't fit into any of the other categories:
781
782* ``|``: Applies a filter.
783
784* ``..``: Creates a sequence based on the operand before and after the operator
785  (this is just syntactic sugar for the :doc:`range<functions/range>` function):
786
787  .. code-block:: jinja
788
789      {{ 1..5 }}
790
791      {# equivalent to #}
792      {{ range(1, 5) }}
793
794  Note that you must use parentheses when combining it with the filter operator
795  due to the :ref:`operator precedence rules <twig-expressions>`:
796
797  .. code-block:: jinja
798
799      (1..5)|join(', ')
800
801* ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
802  " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
803  John!``.
804
805* ``.``, ``[]``: Gets an attribute of an object.
806
807* ``?:``: The ternary operator:
808
809  .. code-block:: jinja
810
811      {{ foo ? 'yes' : 'no' }}
812
813      {# as of Twig 1.12.0 #}
814      {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
815      {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
816
817* ``??``: The null-coalescing operator:
818
819  .. code-block:: jinja
820
821      {# returns the value of foo if it is defined and not null, 'no' otherwise #}
822      {{ foo ?? 'no' }}
823
824String Interpolation
825~~~~~~~~~~~~~~~~~~~~
826
827.. versionadded:: 1.5
828    String interpolation was added in Twig 1.5.
829
830String interpolation (``#{expression}``) allows any valid expression to appear
831within a *double-quoted string*. The result of evaluating that expression is
832inserted into the string:
833
834.. code-block:: jinja
835
836    {{ "foo #{bar} baz" }}
837    {{ "foo #{1 + 2} baz" }}
838
839.. _templates-whitespace-control:
840
841Whitespace Control
842------------------
843
844.. versionadded:: 1.1
845    Tag level whitespace control was added in Twig 1.1.
846
847The first newline after a template tag is removed automatically (like in PHP.)
848Whitespace is not further modified by the template engine, so each whitespace
849(spaces, tabs, newlines etc.) is returned unchanged.
850
851Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
852
853.. code-block:: jinja
854
855    {% spaceless %}
856        <div>
857            <strong>foo bar</strong>
858        </div>
859    {% endspaceless %}
860
861    {# output will be <div><strong>foo bar</strong></div> #}
862
863In addition to the spaceless tag you can also control whitespace on a per tag
864level. By using the whitespace control modifier on your tags, you can trim
865leading and or trailing whitespace:
866
867.. code-block:: jinja
868
869    {% set value = 'no spaces' %}
870    {#- No leading/trailing whitespace -#}
871    {%- if true -%}
872        {{- value -}}
873    {%- endif -%}
874
875    {# output 'no spaces' #}
876
877The above sample shows the default whitespace control modifier, and how you can
878use it to remove whitespace around tags. Trimming space will consume all whitespace
879for that side of the tag.  It is possible to use whitespace trimming on one side
880of a tag:
881
882.. code-block:: jinja
883
884    {% set value = 'no spaces' %}
885    <li>    {{- value }}    </li>
886
887    {# outputs '<li>no spaces    </li>' #}
888
889Extensions
890----------
891
892Twig can be easily extended.
893
894If you are looking for new tags, filters, or functions, have a look at the Twig official
895`extension repository`_.
896
897If you want to create your own, read the :ref:`Creating an
898Extension<creating_extensions>` chapter.
899
900.. _`Twig bundle`:                https://github.com/Anomareh/PHP-Twig.tmbundle
901.. _`Jinja syntax plugin`:        http://jinja.pocoo.org/docs/integration/#vim
902.. _`vim-twig plugin`:            https://github.com/lumiliet/vim-twig
903.. _`Twig syntax plugin`:         http://plugins.netbeans.org/plugin/37069/php-twig
904.. _`Twig plugin`:                https://github.com/pulse00/Twig-Eclipse-Plugin
905.. _`Twig language definition`:   https://github.com/gabrielcorpse/gedit-twig-template-language
906.. _`extension repository`:       https://github.com/twigphp/Twig-extensions
907.. _`Twig syntax mode`:           https://github.com/bobthecow/Twig-HTML.mode
908.. _`other Twig syntax mode`:     https://github.com/muxx/Twig-HTML.mode
909.. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig
910.. _`web-mode.el`:                http://web-mode.org/
911.. _`regular expressions`:        https://secure.php.net/manual/en/pcre.pattern.php
912.. _`PHP-twig for atom`:          https://github.com/reesef/php-twig
913.. _`TwigFiddle`:                 https://twigfiddle.com/
914.. _`Twig pack`:                  https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack
915