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.phpfiles have been replaced by*.html.twigtemplate files.
Printing Variables and Functions
Twig uses syntax to output data.
3will output the integer3.xyzwill output the stringxyzwill output the variablemyvar{{ someFunction }}will output the results ofsomeFunction(){{ someFunction(foo, bar) }}will output the results ofsomeFunction(foo, bar)
Arrays and Objects
Array items and object properties/methods can be accessed using a dot (.):
{{ 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 ([]):``
{{ foo[0] }}
{{ foo['bar'] }}For convenience's sake foo.bar does the following things on the PHP layer:
- check if
foois an array andbara valid element; if not, and iffoois an object, check thatbaris a valid property; - if not, and if
foois an object, check thatbaris a valid method (even ifbaris the constructor - use__construct()instead); - if not, and if
foois an object, check thatgetBaris a valid method; - if not, and if
foois an object, check thatisBaris a valid method; - if not, and if
foois an object, check thathasBaris a valid method; - if not, return a
nullvalue.
foo['bar'] on the other hand only works with PHP arrays:
- check if
foois an array andbara valid element; - if not, return a
nullvalue.
If you need access a dynamic attribute:
{{ attribute(foo, 'data-foo') }}Executing Statements
Twig uses braces{ and percentage % syntax to execute statements.
{% 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.
{% set x = 123 %}
{% set name = 'Name: !name'|t('!name', list.name) %}Conditionally Outputting a Region
{% if message %}
<div class="message">{{ message }}</div>
{% endif %}Looping
<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.
{# Comments go inside these brackets. #}You can also do multiline comments:
{#
This comment spans
multiple lines.
#}A notable use for this is the twig file DocBlock. For example:
{#
/**
* @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.
{{ "Some String"|t }}Here are some common Drupal-specific filters:
trans/t: Runs variable through Drupalt()function. (Note: Do not pass variables through the translation filter as this is a potential security vulnerability.)placeholder: Escapes content to HTML and passes throughdrupal_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 therender()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:
<p class="submitted">
{% trans %}
Submitted by {{ author.name }} on {{ node.date }}
{% endtrans %}
</p>With the {% plural ... %} switch:
{% 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.
{% 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:
{% 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
varargsvariable 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
- drupal.org: Twig in Drupal
- drupal.org: Twig Coding Standards
- drupal.org: Filters - Modifying Variables In Twig Templates
- twig.symfony: Twig Coding Standards
