Twig
Twig is a template engine for PHP. It is used by Drupal to render HTML pages.
Twig is a very powerful tool that allows you to create complex templates with very little code.
Accessing variables
It is recommended to use the dot (.) syntax to access variables.
{{ variable['key'] }} {# This is allowed, but use {{ variable.key }} instead! #}
{{ variable[0] }} {# This is allowed, but use {{ variable.0 instead! }} #}Loops
Using if conditions in loops:
You can limit the items returned in an iteration by adding an if clause. The example below will loop over all rows of the items variable, but only print out those where item.status evaluates to TRUE.
{% for item in items if item.status %}
{{ item.title }}
{% endfor %}Adding Classes
<ul class='blog-post__tags field__items'>
{% for item in items %}
<li{{ item.attributes.addClass('blog-post__tag') }}>{{ item.content }}</li>
{% endfor %}
</ul>Filters and Functions
Drupal has some Drupal-specific Twig functions that are meant to be called within a Twig file.
url($name, $parameters, $options): Generates an absolute URL, given a route name and optional parameters.
path($name, $parameters, $options): Generates a relative URL path given a route name and parameters.
link($text, $url, $attributes): Create a link in HTML.
file_url($uri): Accepts a relative path from the root and creates an absolute path to the file.
Using named arguments with filters
Arguments to filters can be named, so that a filter can be used without specifying a value for all arguments. This is useful when using filters like round, which takes two arguments: round(precision, method). Perhaps you only want to specify a value for the second argument and want to leave the first one as default. Writing your function like the example can make your templates more readable.
Check if variable is not null
## Nodes
Render Node elements and fields
Render Referenced Media Elements
Render multiple field elements
Render/Access List (Text) Field type
Render the label of a select field type
Taxonomies
Render multiple taxonomy terms field
Render Translated content types or Taxonomies
Reference
For more information about Twig, see the Twig documentation. Also here are some useful links that can help you to understand how to use Twig in Drupal 8/9:
Last updated