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