Skip to content

Twig coding standards

Drupal 9 uses TWIG as the templating engine. All the template files are twig files and they need to follow certain Drupal related twig coding practices.

The DocBlock

  • A docblock at the top of a Twig template should be identical to the docblock at the top of a PHPTemplate file.
  • Twig template docblocks should only include @ingroup themeable if the template is providing the default themeable output.
  • For themes overriding default output the @ingroup themeable line should not be included.
{#
/**
 * @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
 */
#}

Variables in the DocBlock

  • Variables in a twig template docblock should be referenced by name.
  • They will not be surrounded by the Twig print indicators {{ and }} and will not be preceded by the PHP variable indicator $.
  • When a variable is referenced in-line in paragraphs the variable name should be wrapped in single quote.

Expressions

  • Twig expressions are very similar to regular PHP expressions, and are most commonly used in Drupal to check if variables are available for printing, for looping, and for setting new variables within templates.
  • Expressions: Checking if variables are available for printing
{% if foo %}
  <div>{{ foo }}</div>
{% endif %}
  • Twig uses for loops, and in Drupal we are used to using foreach loops.
{% for item in navigation %}
  <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
  • Expressions can also be used for setting variables directly in template files.
{% set list = ['Alice', 'Bob'] %}
{% set text = ':person is a Twig fan'|t({':person': list[0] }) %}
  • HTML attributes can be printed all of them at once by printing {{ attributes }} or you can print each attribute individually.
<div id="{{ attributes.id }}" class="{{ attributes.class }}"{{ attributes }}>
  {{ content }}
</div>

Filters

  • Some of the most common Drupal functions like t and url have been made available in your twig templates as filters.
  • Filters are triggered by using the pipe character | .
<div class="preview-image-wrapper">
  {{ 'Original'|t }}
</div>

Comments

  • All comments will be surrounded by the twig comment indicator.
  • Comments that span one line will have the comment indicators on the same line as the comment.
<div class="image-widget-data">
  {# Render widget data without the image preview that was output already. #}
  {{ data|without('preview') }}
</div>