Skip to content

Twig Syntax

From Twig in Drupal 8:

Twig is a template engine for PHP and it is part of the Symfony2 framework.

In Drupal 8 Twig replaces PHPTemplate as the default templating engine. One of the results of this change is that all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced by *.html.twig template files.

Printing Variables and Functions

Twig uses syntax to output data.

  • 3 will output the integer 3.
  • xyz will output the string xyz
  • will output the variable myvar
  • {{ someFunction }} will output the results of someFunction()
  • {{ someFunction(foo, bar) }} will output the results of someFunction(foo, bar)

Arrays and Objects

Array items and object properties/methods can be accessed using a dot (.):

twig
{{ foo.0 }}
{{ foo.bar }}
{{ foo.method }}
{{ foo.method(baz) }}

This allows themers to not worry about variable types, and just output the data.

Array items can also be accessed using the subscript syntax ([]):``

twig
{{ foo[0] }}
{{ foo['bar'] }}

For convenience's sake foo.bar does the following things on the PHP layer:

  • check if foo is an array and bar a valid element; if not, and if foo is an object, check that bar is a valid property;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
  • if not, and if foo is an object, check that getBar is a valid method;
  • if not, and if foo is an object, check that isBar is a valid method;
  • if not, and if foo is an object, check that hasBar is a valid method;
  • if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

  • check if foo is an array and bar a valid element;
  • if not, return a null value.

If you need access a dynamic attribute:

twig
{{ attribute(foo, 'data-foo') }}

Executing Statements

Twig uses braces{ and percentage % syntax to execute statements.

twig
{% if foo %}
  <p>Foo is true</p>
{% endif %}

Setting Variables

The following code sets a variable x to the value of 123 and sets the variable name to the value of Name: !name where !name is replaced with the translated value of list.name.

twig
{% set x = 123 %}
{% set name = 'Name: !name'|t('!name', list.name) %}

Conditionally Outputting a Region

twig
{% if message %}
 <div class="message">{{ message }}</div>
{% endif %}

Looping

twig
<ul>
{% for item in list %}
  <li>{{ item.title }}: ${{item.price}}</li>
{% endfor %}
</ul>

Looping over a list of users

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

The loop.length, loop.revindex, loop.revindex0, and loop.last variables are only available for PHP arrays, or objects that implement the Countable interface.

Commenting

Twig uses {# #} syntax for comments.

twig
{# Comments go inside these brackets. #}

You can also do multiline comments:

twig
{#
  This comment spans
  multiple lines.
#}

A notable use for this is the twig file DocBlock. For example:

twig
{#
/**
 * @file
 * Default theme implementation for a region.
 *
 * Available variables:
 * - content: The content for this region, typically blocks.
 * - attributes: Remaining HTML attributes for the element, including:
 *   - class: HTML classes that can be used to style contextually through CSS.
 *
 * @see template_preprocess_region()
 *
 * @ingroup themeable
 */
#}

Filters

Filters can be used to modify variables and expressions.

twig
{{ "Some String"|t }}

Here are some common Drupal-specific filters:

  • trans/t: Runs variable through Drupal t() function. (Note: Do not pass variables through the translation filter as this is a potential security vulnerability.)
  • placeholder: Escapes content to HTML and passes through drupal_placeholder(), which emphasizes text (i.e. <em>foo</em>).
  • clean_class: Prepares a string for use as a class name.
  • clean_id: Prepares a string for use as an id.
  • format_date: Prepares a timestamp for use as a formatted date.
  • raw: Marks value as being safe which means no escaping will take place. This should be avoided if possible.
  • render: Wrapper for the render() function.
  • safe_join: Joins several strings together with a specified separator (e.g. {{ foo|safe_join('😂 }})
  • without: Duplicates an array, excluding specified keys (e.g. {{ foo|without('bar', 'baz') }})

Twig {% trans %} tag

From Drupal.org - Added support for the Twig {% trans %} tag extension:

The Twig {% trans %} block will translate the text using tokens with t() or format_plural() if the {% plural ... %} switch has been declared in the tag:

twig
<p class="submitted">
{% trans %}
  Submitted by {{ author.name }} on {{ node.date }}
{% endtrans %}
</p>

With the {% plural ... %} switch:

twig
{% set count = comments|length %}
{% trans %}
  {{ count }} comment was deleted successfully.
{% plural count %}
  {{ count }} comments were deleted successfully.
{% endtrans %}

If filtering the tokens inside the {% trans %} block does not work, create a token outside of the block to minimize operations inside.

twig
{% set date = node.created|format_date('medium') %}
{% trans %}
  Node was created on {{ date }}.
{% endtrans %}

Macros

From Twig's official macro documentation:

Macros are comparable with functions in regular programming languages. They are useful to put often used HTML idioms into reusable elements to not repeat yourself.

Here is a small example of a macro that renders a form element:

twig
{% macro input(name, value, type, size) %}
   <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}

Macros differ from native PHP functions in a few ways:

  • Default argument values are defined by using the default filter in the macro body;
  • Arguments of a macro are always optional.
  • If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

But as with PHP functions, macros don't have access to the current template variables.

Questions

What syntax does Twig use to output data in templates?

Answer: Twig uses the {{ }} syntax to output data in templates.

What syntax is used to access arrays and objects in twig?

Answer: The dot syntax foo.bar can be used for both arrays and objects. Array items can also be accessed using the subscript syntax ([]).

What is the purpose of the {% trans %} tag in Twig?

Answer: To translate text using tokens.

Additional Resources