Cheat Sheet
Override a Template and Discover Variables
1. Turn on Twig debugging.
2. View source. Which template is being used?
Look for BEGIN OUTPUT from.
3. Copy the file into your theme's templates directory. Optional: Rename file to change its scope using File Name Suggestions.
4. Clear the cache (Configuration > Performance > Clear all caches or drush cr
)
5. Inspect variables.
Use {{ dump(_context|keys) }}
in template to see which variables are available.
Example Twig Debug Output (View Source)
After turning on Twig debug mode, view source on any page of your Drupal site to see the Twig debug output in HTML comments.
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page'
<!-- FILE NAME SUGGESTIONS:
* page--node--1.html.twig
* page--node--%.html.twig
* page--node.html.twig
x page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/icecream/templates/page.html.twig' -->
Twig Template Example
Learn about template variables in comment blocks
{# Learn about template variables in comment blocks
- items: A list of ice cream flavors
- title: Link title
- author: Author of content
#}
Discover variables with dump().
{# Discover variables with dump(). #}
{{ dump(_context|keys) }}
Attach an asset library in a template
{# Attach an asset library in a template. #}
{{ attach_library('classy/node') }}
Define a variable
{# Define a variable. #}
{% set date = node.created|format_date('long') %}
Add a CSS class
<article{{ attributes.addClass('about') }}>
Make hard-coded text translatable
{# Translatable text with vars, use trans. #}
<p class="byline">{% trans %}by {{ author }} on {{ date }}{% endtrans %}</p>
{# Translatable text without variables, use t. #}
<h3>{{ 'Ice Cream Flavors'|t }}</h3>
Iterate over a list with a for loop
{# Iterate over a list with a for loop. #}
<ul class="ice-cream-list">
{% for item in items %}
<li class="ice-cream-list--flavor">{{ item.title }}</li>
{% endfor %}
</ul>
Create a link in a template
{# Links in templates. If you know the route: #}
<a href="{{ url('contact.site_page') }}">{{ 'Contact'|t }}</a>
{# If you don't know the route: #}
{{ link('Contact'|t, 'base:about/contact', { 'class':[] }) }}
</article>