1 Twig for Template Designers
2 ===========================
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.
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.
14 A template contains **variables** or **expressions**, which get replaced with
15 values when the template is evaluated, and **tags**, which control the logic
18 Below is a minimal template that illustrates a few basics. We will cover further
21 .. code-block:: html+jinja
26 <title>My Webpage</title>
30 {% for item in navigation %}
31 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
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.
47 Many IDEs support syntax highlighting and auto-completion for Twig:
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`_
64 Also, `TwigFiddle`_ is an online service that allows you to execute Twig templates
65 from a browser; it supports all versions of Twig.
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
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 (``[]``):
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:
90 {# equivalent to the non-working foo.data-foo #}
91 {{ attribute(foo, 'data-foo') }}
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.
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>`).
103 .. sidebar:: Implementation
105 For convenience's sake ``foo.bar`` does the following things on the PHP
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.
116 ``foo['bar']`` on the other hand only works with PHP arrays:
118 * check if ``foo`` is an array and ``bar`` a valid element;
119 * if not, return a ``null`` value.
123 If you want to access a dynamic attribute of a variable, use the
124 :doc:`attribute<functions/attribute>` function instead.
129 The following variables are always available in templates:
131 * ``_self``: references the current template;
132 * ``_context``: references the current context;
133 * ``_charset``: references the current charset.
138 You can assign values to variables inside code blocks. Assignments use the
139 :doc:`set<tags/set>` tag:
141 .. code-block:: jinja
143 {% set foo = 'foo' %}
144 {% set foo = [1, 2] %}
145 {% set foo = {'foo': 'bar'} %}
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
155 The following example removes all HTML tags from the ``name`` and title-cases
158 .. code-block:: jinja
160 {{ name|striptags|title }}
162 Filters that accept arguments have parentheses around the arguments. This
163 example will join a list by commas:
165 .. code-block:: jinja
167 {{ list|join(', ') }}
169 To apply a filter on a section of code, wrap it in the
170 :doc:`filter<tags/filter>` tag:
172 .. code-block:: jinja
175 This text becomes uppercase
178 Go to the :doc:`filters<filters/index>` page to learn more about built-in
184 Functions can be called to generate content. Functions are called by their
185 name followed by parentheses (``()``) and may have arguments.
187 For instance, the ``range`` function returns a list containing an arithmetic
188 progression of integers:
190 .. code-block:: jinja
192 {% for i in range(0, 3) %}
196 Go to the :doc:`functions<functions/index>` page to learn more about the
202 .. versionadded:: 1.12
203 Support for named arguments was added in Twig 1.12.
205 .. code-block:: jinja
207 {% for i in range(low=1, high=10, step=2) %}
211 Using named arguments makes your templates more explicit about the meaning of
212 the values you pass as arguments:
214 .. code-block:: jinja
216 {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
220 {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
222 Named arguments also allow you to skip some arguments for which you don't want
223 to change the default value:
225 .. code-block:: jinja
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") }}
230 {# or skip the format value by using a named argument for the time zone #}
231 {{ "now"|date(timezone="Europe/Paris") }}
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:
236 .. code-block:: jinja
238 {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
242 Each function and filter documentation page has a section where the names
243 of all arguments are listed when supported.
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 ``{% ... %}``
253 For example, to display a list of users provided in a variable called
254 ``users``, use the :doc:`for<tags/for>` tag:
256 .. code-block:: jinja
260 {% for user in users %}
261 <li>{{ user.username|e }}</li>
265 The :doc:`if<tags/if>` tag can be used to test an expression:
267 .. code-block:: jinja
269 {% if users|length > 0 %}
271 {% for user in users %}
272 <li>{{ user.username|e }}</li>
277 Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags.
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:
286 .. code-block:: jinja
288 {# note: disabled template because we no longer use this
289 {% for user in users %}
294 Including other Templates
295 -------------------------
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:
300 .. code-block:: jinja
302 {{ include('sidebar.html') }}
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:
308 .. code-block:: jinja
310 {% for box in boxes %}
311 {{ include('render_box.html') }}
314 The included template ``render_box.html`` is able to access the ``box`` variable.
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:
320 .. code-block:: jinja
322 {{ include('sections/articles/sidebar.html') }}
324 This behavior depends on the application embedding Twig.
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
334 Sounds complicated but it is very basic. It's easier to understand it by
335 starting with an example.
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:
340 .. code-block:: html+jinja
346 <link rel="stylesheet" href="style.css" />
347 <title>{% block title %}{% endblock %} - My Webpage</title>
351 <div id="content">{% block content %}{% endblock %}</div>
354 © Copyright 2011 by <a href="http://domain.invalid/">you</a>.
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
365 A child template might look like this:
367 .. code-block:: jinja
369 {% extends "base.html" %}
371 {% block title %}Index{% endblock %}
374 <style type="text/css">
375 .important { color: #336699; }
380 <p class="important">
381 Welcome to my awesome homepage.
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.
390 Note that since the child template doesn't define the ``footer`` block, the
391 value from the parent template is used instead.
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
397 .. code-block:: jinja
400 <h3>Table Of Contents</h3>
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.
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.
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.
425 Twig supports both, automatic escaping is enabled by default.
427 The automatic escaping strategy can be configured via the
428 :ref:`autoescape<environment_options>` option and defaults to ``html``.
430 Working with Manual Escaping
431 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
436 Escaping works by piping the variable through the
437 :doc:`escape<filters/escape>` or ``e`` filter:
439 .. code-block:: jinja
441 {{ user.username|e }}
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
447 .. code-block:: jinja
449 {{ user.username|e('js') }}
450 {{ user.username|e('css') }}
451 {{ user.username|e('url') }}
452 {{ user.username|e('html_attr') }}
454 Working with Automatic Escaping
455 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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>`
461 .. code-block:: jinja
464 Everything will be automatically escaped in this block (using the HTML strategy)
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:
471 .. code-block:: jinja
473 {% autoescape 'js' %}
474 Everything will be automatically escaped in this block (using the JS strategy)
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.
485 The easiest way is to output the variable delimiter (``{{``) by using a variable
488 .. code-block:: jinja
492 For bigger sections it makes sense to mark a block
493 :doc:`verbatim<tags/verbatim>`.
498 .. versionadded:: 1.12
499 Support for default argument values was added in Twig 1.12.
501 Macros are comparable with functions in regular programming languages. They
502 are useful to reuse often used HTML fragments to not repeat yourself.
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:
507 .. code-block:: jinja
509 {% macro input(name, value, type, size) %}
510 <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
513 Macros can be defined in any template, and need to be "imported" via the
514 :doc:`import<tags/import>` tag before being used:
516 .. code-block:: jinja
518 {% import "forms.html" as forms %}
520 <p>{{ forms.input('username') }}</p>
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:
525 .. code-block:: jinja
527 {% from 'forms.html' import input as input_field %}
531 <dd>{{ input_field('username') }}</dd>
533 <dd>{{ input_field('password', '', 'password') }}</dd>
536 A default value can also be defined for macro arguments when not provided in a
539 .. code-block:: jinja
541 {% macro input(name, value = "", type = "text", size = 20) %}
542 <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
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.
548 .. _twig-expressions:
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.
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 ``.``:
564 .. code-block:: jinja
566 {% set greeting = 'Hello ' %}
567 {% set name = 'Fabien' %}
569 {{ greeting ~ name|lower }} {# Hello fabien #}
571 {# use parenthesis to change precedence #}
572 {{ (greeting ~ name)|lower }} {# hello fabien #}
577 .. versionadded:: 1.5
578 Support for hash keys as names and expressions was added in Twig 1.5.
580 The simplest form of expressions are literals. Literals are representations
581 for PHP types such as strings, numbers, and arrays. The following literals
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'``).
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.
596 * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
597 separated by a comma (``,``) and wrapped with squared brackets (``[]``).
599 * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
600 separated by a comma (``,``) and wrapped with curly braces (``{}``):
602 .. code-block:: jinja
605 { 'foo': 'foo', 'bar': 'bar' }
607 {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
608 { foo: 'foo', bar: 'bar' }
610 {# keys as integer #}
611 { 2: 'foo', 4: 'bar' }
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' }
617 * ``true`` / ``false``: ``true`` represents the true value, ``false``
618 represents the false value.
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``.
623 Arrays and hashes can be nested:
625 .. code-block:: jinja
627 {% set foo = [1, {"foo": "bar"}] %}
631 Using double-quoted or single-quoted strings has no impact on performance
632 but string interpolation is only supported in double-quoted strings.
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:
640 * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
643 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
646 * ``/``: Divides two numbers. The returned value will be a floating point
647 number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
649 * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
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).
656 * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
659 * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
660 3 }}`` would return ``8``.
665 You can combine multiple expressions with the following operators:
667 * ``and``: Returns true if the left and the right operands are both true.
669 * ``or``: Returns true if the left or the right operand is true.
671 * ``not``: Negates a statement.
673 * ``(expr)``: Groups an expression.
677 Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
681 Operators are case sensitive.
686 The following comparison operators are supported in any expression: ``==``,
687 ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
689 You can also check if a string ``starts with`` or ``ends with`` another
692 .. code-block:: jinja
694 {% if 'Fabien' starts with 'F' %}
697 {% if 'Fabien' ends with 'n' %}
702 For complex string comparisons, the ``matches`` operator allows you to use
703 `regular expressions`_:
705 .. code-block:: jinja
707 {% if phone matches '/^[\\d\\.]+$/' %}
713 The ``in`` operator performs containment test.
715 It returns ``true`` if the left operand is contained in the right:
717 .. code-block:: jinja
723 {{ 'cd' in 'abcde' }}
727 You can use this filter to perform a containment test on strings, arrays,
728 or objects implementing the ``Traversable`` interface.
730 To perform a negative test, use the ``not in`` operator:
732 .. code-block:: jinja
734 {% if 1 not in [1, 2, 3] %}
736 {# is equivalent to #}
737 {% if not (1 in [1, 2, 3]) %}
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:
745 .. code-block:: jinja
747 {# find out if a variable is odd #}
751 Tests can accept arguments too:
753 .. code-block:: jinja
755 {% if post.status is constant('Post::PUBLISHED') %}
757 Tests can be negated by using the ``is not`` operator:
759 .. code-block:: jinja
761 {% if post.status is not constant('Post::PUBLISHED') %}
763 {# is equivalent to #}
764 {% if not (post.status is constant('Post::PUBLISHED')) %}
766 Go to the :doc:`tests<tests/index>` page to learn more about the built-in
772 .. versionadded:: 1.12.0
773 Support for the extended ternary operator was added in Twig 1.12.0.
775 The following operators don't fit into any of the other categories:
777 * ``|``: Applies a filter.
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):
782 .. code-block:: jinja
789 Note that you must use parentheses when combining it with the filter operator
790 due to the :ref:`operator precedence rules <twig-expressions>`:
792 .. code-block:: jinja
796 * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
797 " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
800 * ``.``, ``[]``: Gets an attribute of an object.
802 * ``?:``: The ternary operator:
804 .. code-block:: jinja
806 {{ foo ? 'yes' : 'no' }}
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' : '' }}
812 * ``??``: The null-coalescing operator:
814 .. code-block:: jinja
816 {# returns the value of foo if it is defined and not null, 'no' otherwise #}
822 .. versionadded:: 1.5
823 String interpolation was added in Twig 1.5.
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:
829 .. code-block:: jinja
831 {{ "foo #{bar} baz" }}
832 {{ "foo #{1 + 2} baz" }}
834 .. _templates-whitespace-control:
839 .. versionadded:: 1.1
840 Tag level whitespace control was added in Twig 1.1.
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.
846 Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
848 .. code-block:: jinja
852 <strong>foo bar</strong>
856 {# output will be <div><strong>foo bar</strong></div> #}
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:
862 .. code-block:: jinja
864 {% set value = 'no spaces' %}
865 {#- No leading/trailing whitespace -#}
870 {# output 'no spaces' #}
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
877 .. code-block:: jinja
879 {% set value = 'no spaces' %}
880 <li> {{- value }} </li>
882 {# outputs '<li>no spaces </li>' #}
887 Twig can be easily extended.
889 If you are looking for new tags, filters, or functions, have a look at the Twig official
890 `extension repository`_.
892 If you want to create your own, read the :ref:`Creating an
893 Extension<creating_extensions>` chapter.
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