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 the
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`_
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`_
65 The application passes variables to the templates you can mess around in the
66 template. Variables may have attributes or elements on them you can access
67 too. How a variable looks like heavily depends on the application providing
70 You can use a dot (``.``) to access attributes of a variable (methods or
71 properties of a PHP object, or items of a PHP array), or the so-called
72 "subscript" syntax (``[]``):
79 When the attribute contains special characters (like ``-`` that would be
80 interpreted as the minus operator), use the ``attribute`` function instead to
81 access the variable attribute:
85 {# equivalent to the non-working foo.data-foo #}
86 {{ attribute(foo, 'data-foo') }}
90 It's important to know that the curly braces are *not* part of the
91 variable but the print statement. If you access variables inside tags
92 don't put the braces around.
94 If a variable or attribute does not exist, you will get back a ``null`` value
95 when the ``strict_variables`` option is set to ``false``, otherwise Twig will
96 throw an error (see :ref:`environment options<environment_options>`).
98 .. sidebar:: Implementation
100 For convenience sake ``foo.bar`` does the following things on the PHP
103 * check if ``foo`` is an array and ``bar`` a valid element;
104 * if not, and if ``foo`` is an object, check that ``bar`` is a valid property;
105 * if not, and if ``foo`` is an object, check that ``bar`` is a valid method
106 (even if ``bar`` is the constructor - use ``__construct()`` instead);
107 * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method;
108 * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
109 * if not, return a ``null`` value.
111 ``foo['bar']`` on the other hand only works with PHP arrays:
113 * check if ``foo`` is an array and ``bar`` a valid element;
114 * if not, return a ``null`` value.
118 If you want to get a dynamic attribute on a variable, use the
119 :doc:`attribute<functions/attribute>` function instead.
124 The following variables are always available in templates:
126 * ``_self``: references the current template;
127 * ``_context``: references the current context;
128 * ``_charset``: references the current charset.
133 You can assign values to variables inside code blocks. Assignments use the
134 :doc:`set<tags/set>` tag:
136 .. code-block:: jinja
138 {% set foo = 'foo' %}
139 {% set foo = [1, 2] %}
140 {% set foo = {'foo': 'bar'} %}
145 Variables can be modified by **filters**. Filters are separated from the
146 variable by a pipe symbol (``|``) and may have optional arguments in
147 parentheses. Multiple filters can be chained. The output of one filter is
150 The following example removes all HTML tags from the ``name`` and title-cases
153 .. code-block:: jinja
155 {{ name|striptags|title }}
157 Filters that accept arguments have parentheses around the arguments. This
158 example will join a list by commas:
160 .. code-block:: jinja
162 {{ list|join(', ') }}
164 To apply a filter on a section of code, wrap it with the
165 :doc:`filter<tags/filter>` tag:
167 .. code-block:: jinja
170 This text becomes uppercase
173 Go to the :doc:`filters<filters/index>` page to learn more about the built-in
179 Functions can be called to generate content. Functions are called by their
180 name followed by parentheses (``()``) and may have arguments.
182 For instance, the ``range`` function returns a list containing an arithmetic
183 progression of integers:
185 .. code-block:: jinja
187 {% for i in range(0, 3) %}
191 Go to the :doc:`functions<functions/index>` page to learn more about the
197 .. versionadded:: 1.12
198 Support for named arguments was added in Twig 1.12.
200 Arguments for filters and functions can also be passed as *named arguments*:
202 .. code-block:: jinja
204 {% for i in range(low=1, high=10, step=2) %}
208 Using named arguments makes your templates more explicit about the meaning of
209 the values you pass as arguments:
211 .. code-block:: jinja
213 {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
217 {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
219 Named arguments also allow you to skip some arguments for which you don't want
220 to change the default value:
222 .. code-block:: jinja
224 {# the first argument is the date format, which defaults to the global date format if null is passed #}
225 {{ "now"|date(null, "Europe/Paris") }}
227 {# or skip the format value by using a named argument for the timezone #}
228 {{ "now"|date(timezone="Europe/Paris") }}
230 You can also use both positional and named arguments in one call, in which
231 case positional arguments must always come before named arguments:
233 .. code-block:: jinja
235 {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
239 Each function and filter documentation page has a section where the names
240 of all arguments are listed when supported.
245 A control structure refers to all those things that control the flow of a
246 program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as
247 well as things like blocks. Control structures appear inside ``{% ... %}``
250 For example, to display a list of users provided in a variable called
251 ``users``, use the :doc:`for<tags/for>` tag:
253 .. code-block:: jinja
257 {% for user in users %}
258 <li>{{ user.username|e }}</li>
262 The :doc:`if<tags/if>` tag can be used to test an expression:
264 .. code-block:: jinja
266 {% if users|length > 0 %}
268 {% for user in users %}
269 <li>{{ user.username|e }}</li>
274 Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags.
279 To comment-out part of a line in a template, use the comment syntax ``{# ...
280 #}``. This is useful for debugging or to add information for other template
281 designers or yourself:
283 .. code-block:: jinja
285 {# note: disabled template because we no longer use this
286 {% for user in users %}
291 Including other Templates
292 -------------------------
294 The :doc:`include<tags/include>` tag is useful to include a template and
295 return the rendered content of that template into the current one:
297 .. code-block:: jinja
299 {% include 'sidebar.html' %}
301 Per default included templates are passed the current context.
303 The context that is passed to the included template includes variables defined
306 .. code-block:: jinja
308 {% for box in boxes %}
309 {% include "render_box.html" %}
312 The included template ``render_box.html`` is able to access ``box``.
314 The filename of the template depends on the template loader. For instance, the
315 ``Twig_Loader_Filesystem`` allows you to access other templates by giving the
316 filename. You can access templates in subdirectories with a slash:
318 .. code-block:: jinja
320 {% include "sections/articles/sidebar.html" %}
322 This behavior depends on the application embedding Twig.
327 The most powerful part of Twig is template inheritance. Template inheritance
328 allows you to build a base "skeleton" template that contains all the common
329 elements of your site and defines **blocks** that child templates can
332 Sounds complicated but is very basic. It's easier to understand it by
333 starting with an example.
335 Let's define a base template, ``base.html``, which defines a simple HTML
336 skeleton document that you might use for a simple two-column page:
338 .. code-block:: html+jinja
344 <link rel="stylesheet" href="style.css" />
345 <title>{% block title %}{% endblock %} - My Webpage</title>
349 <div id="content">{% block content %}{% endblock %}</div>
352 © Copyright 2011 by <a href="http://domain.invalid/">you</a>.
358 In this example, the :doc:`block<tags/block>` tags define four blocks that
359 child templates can fill in. All the ``block`` tag does is to tell the
360 template engine that a child template may override those portions of the
363 A child template might look like this:
365 .. code-block:: jinja
367 {% extends "base.html" %}
369 {% block title %}Index{% endblock %}
372 <style type="text/css">
373 .important { color: #336699; }
378 <p class="important">
379 Welcome to my awesome homepage.
383 The :doc:`extends<tags/extends>` tag is the key here. It tells the template
384 engine that this template "extends" another template. When the template system
385 evaluates this template, first it locates the parent. The extends tag should
386 be the first tag in the template.
388 Note that since the child template doesn't define the ``footer`` block, the
389 value from the parent template is used instead.
391 It's possible to render the contents of the parent block by using the
392 :doc:`parent<functions/parent>` function. This gives back the results of the
395 .. code-block:: jinja
398 <h3>Table Of Contents</h3>
405 The documentation page for the :doc:`extends<tags/extends>` tag describes
406 more advanced features like block nesting, scope, dynamic inheritance, and
407 conditional inheritance.
411 Twig also supports multiple inheritance with the so called horizontal reuse
412 with the help of the :doc:`use<tags/use>` tag. This is an advanced feature
413 hardly ever needed in regular templates.
418 When generating HTML from templates, there's always a risk that a variable
419 will include characters that affect the resulting HTML. There are two
420 approaches: manually escaping each variable or automatically escaping
421 everything by default.
423 Twig supports both, automatic escaping is enabled by default.
427 Automatic escaping is only supported if the *escaper* extension has been
428 enabled (which is the default).
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 .. _twig-expressions:
550 Twig allows expressions everywhere. These work very similar to regular PHP and
551 even if you're not working with PHP you should feel comfortable with it.
555 The operator precedence is as follows, with the lowest-precedence
556 operators listed first: ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``,
557 ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``..``, ``+``,
558 ``-``, ``~``, ``*``, ``/``, ``//``, ``%``, ``is``, ``**``, ``|``, ``[]``,
561 .. code-block:: jinja
563 {% set greeting = 'Hello' %}
564 {% set name = 'Fabien' %}
566 {{ greeting ~ name|lower }} {# Hello fabien #}
568 {# use parenthesis to change precedence #}
569 {{ (greeting ~ name)|lower }} {# hello fabien #}
574 .. versionadded:: 1.5
575 Support for hash keys as names and expressions was added in Twig 1.5.
577 The simplest form of expressions are literals. Literals are representations
578 for PHP types such as strings, numbers, and arrays. The following literals
581 * ``"Hello World"``: Everything between two double or single quotes is a
582 string. They are useful whenever you need a string in the template (for
583 example as arguments to function calls, filters or just to extend or include
584 a template). A string can contain a delimiter if it is preceded by a
585 backslash (``\``) -- like in ``'It\'s good'``.
587 * ``42`` / ``42.23``: Integers and floating point numbers are created by just
588 writing the number down. If a dot is present the number is a float,
589 otherwise an integer.
591 * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
592 separated by a comma (``,``) and wrapped with squared brackets (``[]``).
594 * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
595 separated by a comma (``,``) and wrapped with curly braces (``{}``):
597 .. code-block:: jinja
600 { 'foo': 'foo', 'bar': 'bar' }
602 {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
603 { foo: 'foo', bar: 'bar' }
605 {# keys as integer #}
606 { 2: 'foo', 4: 'bar' }
608 {# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
609 { (1 + 1): 'foo', (a ~ 'b'): 'bar' }
611 * ``true`` / ``false``: ``true`` represents the true value, ``false``
612 represents the false value.
614 * ``null``: ``null`` represents no specific value. This is the value returned
615 when a variable does not exist. ``none`` is an alias for ``null``.
617 Arrays and hashes can be nested:
619 .. code-block:: jinja
621 {% set foo = [1, {"foo": "bar"}] %}
625 Using double-quoted or single-quoted strings has no impact on performance
626 but string interpolation is only supported in double-quoted strings.
631 Twig allows you to calculate with values. This is rarely useful in templates
632 but exists for completeness' sake. The following operators are supported:
634 * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
637 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
640 * ``/``: Divides two numbers. The returned value will be a floating point
641 number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
643 * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
646 * ``//``: Divides two numbers and returns the truncated integer result. ``{{
647 20 // 7 }}`` is ``2``.
649 * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
652 * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
653 3 }}`` would return ``8``.
658 You can combine multiple expressions with the following operators:
660 * ``and``: Returns true if the left and the right operands are both true.
662 * ``or``: Returns true if the left or the right operand is true.
664 * ``not``: Negates a statement.
666 * ``(expr)``: Groups an expression.
670 Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
675 The following comparison operators are supported in any expression: ``==``,
676 ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
681 The ``in`` operator performs containment test.
683 It returns ``true`` if the left operand is contained in the right:
685 .. code-block:: jinja
691 {{ 'cd' in 'abcde' }}
695 You can use this filter to perform a containment test on strings, arrays,
696 or objects implementing the ``Traversable`` interface.
698 To perform a negative test, use the ``not in`` operator:
700 .. code-block:: jinja
702 {% if 1 not in [1, 2, 3] %}
704 {# is equivalent to #}
705 {% if not (1 in [1, 2, 3]) %}
710 The ``is`` operator performs tests. Tests can be used to test a variable against
711 a common expression. The right operand is name of the test:
713 .. code-block:: jinja
715 {# find out if a variable is odd #}
719 Tests can accept arguments too:
721 .. code-block:: jinja
723 {% if loop.index is divisibleby(3) %}
725 Tests can be negated by using the ``is not`` operator:
727 .. code-block:: jinja
729 {% if loop.index is not divisibleby(3) %}
731 {# is equivalent to #}
732 {% if not (loop.index is divisibleby(3)) %}
734 Go to the :doc:`tests<tests/index>` page to learn more about the built-in
740 .. versionadded:: 1.12.0
741 Support for the extended ternary operator was added in Twig 1.12.0.
743 The following operators are very useful but don't fit into any of the other
746 * ``..``: Creates a sequence based on the operand before and after the
747 operator (this is just syntactic sugar for the :doc:`range<functions/range>`
750 * ``|``: Applies a filter.
752 * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
753 " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
756 * ``.``, ``[]``: Gets an attribute of an object.
758 * ``?:``: The ternary operator:
760 .. code-block:: jinja
762 {{ foo ? 'yes' : 'no' }}
764 {# as of Twig 1.12.0 #}
765 {{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
766 {{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}
771 .. versionadded:: 1.5
772 String interpolation was added in Twig 1.5.
774 String interpolation (`#{expression}`) allows any valid expression to appear
775 within a *double-quoted string*. The result of evaluating that expression is
776 inserted into the string:
778 .. code-block:: jinja
780 {{ "foo #{bar} baz" }}
781 {{ "foo #{1 + 2} baz" }}
786 .. versionadded:: 1.1
787 Tag level whitespace control was added in Twig 1.1.
789 The first newline after a template tag is removed automatically (like in PHP.)
790 Whitespace is not further modified by the template engine, so each whitespace
791 (spaces, tabs, newlines etc.) is returned unchanged.
793 Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
795 .. code-block:: jinja
799 <strong>foo bar</strong>
803 {# output will be <div><strong>foo bar</strong></div> #}
805 In addition to the spaceless tag you can also control whitespace on a per tag
806 level. By using the whitespace control modifier on your tags, you can trim
807 leading and or trailing whitespace:
809 .. code-block:: jinja
811 {% set value = 'no spaces' %}
812 {#- No leading/trailing whitespace -#}
817 {# output 'no spaces' #}
819 The above sample shows the default whitespace control modifier, and how you can
820 use it to remove whitespace around tags. Trimming space will consume all whitespace
821 for that side of the tag. It is possible to use whitespace trimming on one side
824 .. code-block:: jinja
826 {% set value = 'no spaces' %}
827 <li> {{- value }} </li>
829 {# outputs '<li>no spaces </li>' #}
834 Twig can be easily extended.
836 If you are looking for new tags, filters, or functions, have a look at the Twig official
837 `extension repository`_.
839 If you want to create your own, read the :ref:`Creating an
840 Extension<creating_extensions>` chapter.
842 .. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle
843 .. _`Jinja syntax plugin`: http://jinja.pocoo.org/2/documentation/integration
844 .. _`Twig syntax plugin`: http://plugins.netbeans.org/plugin/37069/php-twig
845 .. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin
846 .. _`Twig language definition`: https://github.com/gabrielcorpse/gedit-twig-template-language
847 .. _`extension repository`: http://github.com/fabpot/Twig-extensions
848 .. _`Twig syntax mode`: https://github.com/bobthecow/Twig-HTML.mode
849 .. _`other Twig syntax mode`: https://github.com/muxx/Twig-HTML.mode
850 .. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig
851 .. _`web-mode.el`: http://web-mode.org/