Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Themes and Twig

Twig Syntax Basics

Learn the Twig template language used by Drupal: printing variables, filters, if and for, whitespace, comments, escaping and Drupal-specific helpers like trans and attributes.

Twig is the template language Drupal uses for every piece of HTML it outputs. It is small, safe by default and designed so templates contain presentation only. If you can read HTML, you can read Twig after about ten minutes: there are just three kinds of markers.

  • {{ ... }} prints something.
  • {% ... %} does something (conditions, loops, setting variables).
  • {# ... #} is a comment that never reaches the browser.

Drupal itself cannot run on this site, so the templates below are read-only. The TryIt blocks contain a tiny Twig-like renderer in JavaScript that reproduces printing, filters and escaping, to build your intuition.

Printing variables

Drupal passes variables to every template. In a node template you will find label, content, url, date and node:

HTML
<article class="article">
  <h2><a href="{{ url }}">{{ label }}</a></h2>
  <p class="meta">By {{ author_name }} on {{ date }}</p>
  {{ content.body }}
</article>

Dots reach inside things. content.body is the body field's render array, node.getTitle() calls a method (you can write node.title.value for field values), and node.field_tags[0] indexes a list. If something does not exist Twig prints nothing instead of failing.

Automatic escaping

Twig escapes variables by default, so {{ title }} containing <script> is printed as harmless text. That is a core security feature. Drupal's own render arrays, such as content, are already safe markup, so they are not double-escaped. The filter |raw turns escaping off and should almost never appear in a theme; use it only for HTML you are certain is safe.

Node.js Stand-in: escaping and printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Filters

A filter transforms a value and is applied with a pipe:

HTML
{{ label|upper }}
{{ date|date('F j, Y') }}
{{ body_text|striptags|slice(0, 120) }}...
{{ tags|join(', ') }}
{{ title|default('Untitled') }}
{{ items|length }} items

Common ones: upper, lower, capitalize, trim, length, join, default, date, slice, first, last, keys, merge, replace, striptags. Drupal adds t and trans for translation, clean_class and clean_id for safe class/ID strings, render, without (hide parts of a render array) and format_date.

Conditions and loops

HTML
{% if page.sidebar %}
  <aside>{{ page.sidebar }}</aside>
{% elseif is_front %}
  <p>Welcome home.</p>
{% else %}
  <p>No sidebar.</p>
{% endif %}

<ul>
{% for item in items %}
  <li class="{{ loop.first ? 'first' }}">{{ loop.index }}. {{ item.content }}</li>
{% else %}
  <li>No items.</li>
{% endfor %}
</ul>

loop is available inside every for: loop.index (starts at 1), loop.index0, loop.first, loop.last, loop.length. An else inside for runs when the list is empty. Comparison and logic use ==, !=, <, and, or, not, in and is empty:

HTML
{% if tags is not empty and 'drupal' in tags %}...{% endif %}
Node.js Stand-in: filters, loops and loop variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Variables, macros and including files

Set your own variables and build class lists:

HTML
{% set classes = ['card', is_front ? 'card--home', node.isPromoted() ? 'card--promoted'] %}
<div{{ attributes.addClass(classes) }}>

attributes is a Drupal object that holds the element's HTML attributes. Printing it as <div{{ attributes }}> keeps classes and IDs that modules add. Always use it on the outer element of a template.

Reuse markup with include, passing only what you want:

HTML
{% include '@sunrise/components/badge.html.twig' with { text: 'New', type: 'success' } only %}

only stops the included file from seeing the parent's variables, which keeps components predictable. extends and block let a template wrap a base layout; embed combines both.

Translation

Anything user-visible should be translatable:

HTML
<a href="{{ url }}">{{ 'Read more'|t }}</a>
<p>{% trans %}Posted {{ count }} comments{% endtrans %}</p>

Debugging

In sites/default/services.yml set twig.config: { debug: true, auto_reload: true, cache: false } for development. HTML comments will then list every template and suggestion that was considered, the one used being marked with an x. You can also dump data with {{ dump(variable) }} when the Devel or Twig Tweak module is installed (kint in Devel). Never leave debug on in production.

Common mistakes

  • Using |raw on user input, which defeats escaping.
  • Printing {{ content }} and then individual fields: fields printed first are cached as rendered. Use {{ content|without('field_image') }} to print the rest.
  • Forgetting {{ attributes }}, so classes from modules vanish.
  • Putting logic in Twig that belongs in a preprocess function, covered in preprocess functions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which delimiter prints a value in Twig?

    Double curly braces print an expression; percent tags run statements; hash tags are comments.
  2. 2. What happens when you print a variable that contains a script tag, without any filter?

    Twig autoescapes by default, which protects against cross-site scripting.
  3. 3. What does the loop.index variable contain inside a for loop?

    loop.index starts at 1; loop.index0 is zero-based.
  4. 4. Why print attributes on the outer element?

    The attributes object carries HTML attributes assembled by Drupal and modules.

Summary

  • {{ }} prints, {% %} controls, {# #} comments.
  • Output is escaped by default; avoid |raw.
  • Filters (upper, join, default, t) transform values; for gives you loop.
  • Use attributes, include ... only and |t for clean, translatable templates.
  • Turn on Twig debug while developing, never in production.

Next: Template Suggestions and Overrides