3d60779a09b2df75051f06aa29651fa6841ec681
[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     {% set foo = 'foo' %}
615     { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
616
617 * ``true`` / ``false``: ``true`` represents the true value, ``false``
618   represents the false value.
619
620 * ``null``: ``null`` represents no specific value. This is the value returned
621   when a variable does not exist. ``none`` is an alias for ``null``.
622
623 Arrays and hashes can be nested:
624
625 .. code-block:: jinja
626
627     {% set foo = [1, {"foo": "bar"}] %}
628
629 .. tip::
630
631     Using double-quoted or single-quoted strings has no impact on performance
632     but string interpolation is only supported in double-quoted strings.
633
634 Math
635 ~~~~
636
637 Twig allows you to calculate with values. This is rarely useful in templates
638 but exists for completeness' sake. The following operators are supported:
639
640 * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
641   1 + 1 }}`` is ``2``.
642
643 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
644   ``1``.
645
646 * ``/``: Divides two numbers. The returned value will be a floating point
647   number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
648
649 * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
650   ``4``.
651
652 * ``//``: Divides two numbers and returns the floored integer result. ``{{ 20
653   // 7 }}`` is ``2``, ``{{ -20  // 7 }}`` is ``-3`` (this is just syntactic
654   sugar for the :doc:`round<filters/round>` filter).
655
656 * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
657   return ``4``.
658
659 * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
660   3 }}`` would return ``8``.
661
662 Logic
663 ~~~~~
664
665 You can combine multiple expressions with the following operators:
666
667 * ``and``: Returns true if the left and the right operands are both true.
668
669 * ``or``: Returns true if the left or the right operand is true.
670
671 * ``not``: Negates a statement.
672
673 * ``(expr)``: Groups an expression.
674
675 .. note::
676
677     Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
678
679 .. note::
680
681     Operators are case sensitive.
682
683 Comparisons
684 ~~~~~~~~~~~
685
686 The following comparison operators are supported in any expression: ``==``,
687 ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
688
689 You can also check if a string ``starts with`` or ``ends with`` another
690 string:
691
692 .. code-block:: jinja
693
694     {% if 'Fabien' starts with 'F' %}
695     {% endif %}
696
697     {% if 'Fabien' ends with 'n' %}
698     {% endif %}
699
700 .. note::
701
702     For complex string comparisons, the ``matches`` operator allows you to use
703     `regular expressions`_:
704
705     .. code-block:: jinja
706
707         {% if phone matches '/^[\\d\\.]+$/' %}
708         {% endif %}
709
710 Containment Operator
711 ~~~~~~~~~~~~~~~~~~~~
712
713 The ``in`` operator performs containment test.
714
715 It returns ``true`` if the left operand is contained in the right:
716
717 .. code-block:: jinja
718
719     {# returns true #}
720
721     {{ 1 in [1, 2, 3] }}
722
723     {{ 'cd' in 'abcde' }}
724
725 .. tip::
726
727     You can use this filter to perform a containment test on strings, arrays,
728     or objects implementing the ``Traversable`` interface.
729
730 To perform a negative test, use the ``not in`` operator:
731
732 .. code-block:: jinja
733
734     {% if 1 not in [1, 2, 3] %}
735
736     {# is equivalent to #}
737     {% if not (1 in [1, 2, 3]) %}
738
739 Test Operator
740 ~~~~~~~~~~~~~
741
742 The ``is`` operator performs tests. Tests can be used to test a variable against
743 a common expression. The right operand is name of the test:
744
745 .. code-block:: jinja
746
747     {# find out if a variable is odd #}
748
749     {{ name is odd }}
750
751 Tests can accept arguments too:
752
753 .. code-block:: jinja
754
755     {% if post.status is constant('Post::PUBLISHED') %}
756
757 Tests can be negated by using the ``is not`` operator:
758
759 .. code-block:: jinja
760
761     {% if post.status is not constant('Post::PUBLISHED') %}
762
763     {# is equivalent to #}
764     {% if not (post.status is constant('Post::PUBLISHED')) %}
765
766 Go to the :doc:`tests<tests/index>` page to learn more about the built-in
767 tests.
768
769 Other Operators
770 ~~~~~~~~~~~~~~~
771
772 .. versionadded:: 1.12.0
773     Support for the extended ternary operator was added in Twig 1.12.0.
774
775 The following operators don't fit into any of the other categories:
776
777 * ``|``: Applies a filter.
778
779 * ``..``: Creates a sequence based on the operand before and after the operator
780   (this is just syntactic sugar for the :doc:`range<functions/range>` function):
781
782   .. code-block:: jinja
783
784       {{ 1..5 }}
785
786       {# equivalent to #}
787       {{ range(1, 5) }}
788
789   Note that you must use parentheses when combining it with the filter operator
790   due to the :ref:`operator precedence rules <twig-expressions>`:
791
792   .. code-block:: jinja
793
794       (1..5)|join(', ')
795
796 * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
797   " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
798   John!``.
799
800 * ``.``, ``[]``: Gets an attribute of an object.
801
802 * ``?:``: The ternary operator:
803
804   .. code-block:: jinja
805
806       {{ foo ? 'yes' : 'no' }}
807
808       {# as of Twig 1.12.0 #}
809       {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
810       {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
811
812 * ``??``: The null-coalescing operator:
813
814   .. code-block:: jinja
815
816       {# returns the value of foo if it is defined and not null, 'no' otherwise #}
817       {{ foo ?? 'no' }}
818
819 String Interpolation
820 ~~~~~~~~~~~~~~~~~~~~
821
822 .. versionadded:: 1.5
823     String interpolation was added in Twig 1.5.
824
825 String interpolation (``#{expression}``) allows any valid expression to appear
826 within a *double-quoted string*. The result of evaluating that expression is
827 inserted into the string:
828
829 .. code-block:: jinja
830
831     {{ "foo #{bar} baz" }}
832     {{ "foo #{1 + 2} baz" }}
833
834 .. _templates-whitespace-control:
835
836 Whitespace Control
837 ------------------
838
839 .. versionadded:: 1.1
840     Tag level whitespace control was added in Twig 1.1.
841
842 The first newline after a template tag is removed automatically (like in PHP.)
843 Whitespace is not further modified by the template engine, so each whitespace
844 (spaces, tabs, newlines etc.) is returned unchanged.
845
846 Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
847
848 .. code-block:: jinja
849
850     {% spaceless %}
851         <div>
852             <strong>foo bar</strong>
853         </div>
854     {% endspaceless %}
855
856     {# output will be <div><strong>foo bar</strong></div> #}
857
858 In addition to the spaceless tag you can also control whitespace on a per tag
859 level. By using the whitespace control modifier on your tags, you can trim
860 leading and or trailing whitespace:
861
862 .. code-block:: jinja
863
864     {% set value = 'no spaces' %}
865     {#- No leading/trailing whitespace -#}
866     {%- if true -%}
867         {{- value -}}
868     {%- endif -%}
869
870     {# output 'no spaces' #}
871
872 The above sample shows the default whitespace control modifier, and how you can
873 use it to remove whitespace around tags. Trimming space will consume all whitespace
874 for that side of the tag.  It is possible to use whitespace trimming on one side
875 of a tag:
876
877 .. code-block:: jinja
878
879     {% set value = 'no spaces' %}
880     <li>    {{- value }}    </li>
881
882     {# outputs '<li>no spaces    </li>' #}
883
884 Extensions
885 ----------
886
887 Twig can be easily extended.
888
889 If you are looking for new tags, filters, or functions, have a look at the Twig official
890 `extension repository`_.
891
892 If you want to create your own, read the :ref:`Creating an
893 Extension<creating_extensions>` chapter.
894
895 .. _`Twig bundle`:                https://github.com/Anomareh/PHP-Twig.tmbundle
896 .. _`Jinja syntax plugin`:        http://jinja.pocoo.org/docs/integration/#vim
897 .. _`vim-twig plugin`:            https://github.com/lumiliet/vim-twig
898 .. _`Twig syntax plugin`:         http://plugins.netbeans.org/plugin/37069/php-twig
899 .. _`Twig plugin`:                https://github.com/pulse00/Twig-Eclipse-Plugin
900 .. _`Twig language definition`:   https://github.com/gabrielcorpse/gedit-twig-template-language
901 .. _`extension repository`:       http://github.com/twigphp/Twig-extensions
902 .. _`Twig syntax mode`:           https://github.com/bobthecow/Twig-HTML.mode
903 .. _`other Twig syntax mode`:     https://github.com/muxx/Twig-HTML.mode
904 .. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig
905 .. _`web-mode.el`:                http://web-mode.org/
906 .. _`regular expressions`:        http://php.net/manual/en/pcre.pattern.php
907 .. _`PHP-twig for atom`:          https://github.com/reesef/php-twig
908 .. _`TwigFiddle`:                 http://twigfiddle.com/
909 .. _`Twig pack`:                  https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack