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 { (1 + 1): 'foo', (a ~ 'b'): 'bar' }
616 * ``true`` / ``false``: ``true`` represents the true value, ``false``
617 represents the false value.
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``.
622 Arrays and hashes can be nested:
624 .. code-block:: jinja
626 {% set foo = [1, {"foo": "bar"}] %}
630 Using double-quoted or single-quoted strings has no impact on performance
631 but string interpolation is only supported in double-quoted strings.
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:
639 * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
642 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
645 * ``/``: Divides two numbers. The returned value will be a floating point
646 number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
648 * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
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).
655 * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
658 * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
659 3 }}`` would return ``8``.
664 You can combine multiple expressions with the following operators:
666 * ``and``: Returns true if the left and the right operands are both true.
668 * ``or``: Returns true if the left or the right operand is true.
670 * ``not``: Negates a statement.
672 * ``(expr)``: Groups an expression.
676 Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
680 Operators are case sensitive.
685 The following comparison operators are supported in any expression: ``==``,
686 ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
688 You can also check if a string ``starts with`` or ``ends with`` another
691 .. code-block:: jinja
693 {% if 'Fabien' starts with 'F' %}
696 {% if 'Fabien' ends with 'n' %}
701 For complex string comparisons, the ``matches`` operator allows you to use
702 `regular expressions`_:
704 .. code-block:: jinja
706 {% if phone matches '/^[\\d\\.]+$/' %}
712 The ``in`` operator performs containment test.
714 It returns ``true`` if the left operand is contained in the right:
716 .. code-block:: jinja
722 {{ 'cd' in 'abcde' }}
726 You can use this filter to perform a containment test on strings, arrays,
727 or objects implementing the ``Traversable`` interface.
729 To perform a negative test, use the ``not in`` operator:
731 .. code-block:: jinja
733 {% if 1 not in [1, 2, 3] %}
735 {# is equivalent to #}
736 {% if not (1 in [1, 2, 3]) %}
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:
744 .. code-block:: jinja
746 {# find out if a variable is odd #}
750 Tests can accept arguments too:
752 .. code-block:: jinja
754 {% if post.status is constant('Post::PUBLISHED') %}
756 Tests can be negated by using the ``is not`` operator:
758 .. code-block:: jinja
760 {% if post.status is not constant('Post::PUBLISHED') %}
762 {# is equivalent to #}
763 {% if not (post.status is constant('Post::PUBLISHED')) %}
765 Go to the :doc:`tests<tests/index>` page to learn more about the built-in
771 .. versionadded:: 1.12.0
772 Support for the extended ternary operator was added in Twig 1.12.0.
774 The following operators don't fit into any of the other categories:
776 * ``|``: Applies a filter.
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):
781 .. code-block:: jinja
788 Note that you must use parentheses when combining it with the filter operator
789 due to the :ref:`operator precedence rules <twig-expressions>`:
791 .. code-block:: jinja
795 * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
796 " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
799 * ``.``, ``[]``: Gets an attribute of an object.
801 * ``?:``: The ternary operator:
803 .. code-block:: jinja
805 {{ foo ? 'yes' : 'no' }}
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' : '' }}
811 * ``??``: The null-coalescing operator:
813 .. code-block:: jinja
815 {# returns the value of foo if it is defined and not null, 'no' otherwise #}
821 .. versionadded:: 1.5
822 String interpolation was added in Twig 1.5.
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:
828 .. code-block:: jinja
830 {{ "foo #{bar} baz" }}
831 {{ "foo #{1 + 2} baz" }}
833 .. _templates-whitespace-control:
838 .. versionadded:: 1.1
839 Tag level whitespace control was added in Twig 1.1.
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.
845 Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
847 .. code-block:: jinja
851 <strong>foo bar</strong>
855 {# output will be <div><strong>foo bar</strong></div> #}
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:
861 .. code-block:: jinja
863 {% set value = 'no spaces' %}
864 {#- No leading/trailing whitespace -#}
869 {# output 'no spaces' #}
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
876 .. code-block:: jinja
878 {% set value = 'no spaces' %}
879 <li> {{- value }} </li>
881 {# outputs '<li>no spaces </li>' #}
886 Twig can be easily extended.
888 If you are looking for new tags, filters, or functions, have a look at the Twig official
889 `extension repository`_.
891 If you want to create your own, read the :ref:`Creating an
892 Extension<creating_extensions>` chapter.
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