Debugging Drupal 8 Twig templates with Xdebug

February 19th, 2018

Ever wondered what variables live in your Drupal 8 templates and how to debug them properly? 🤔
Enabling twig debugging in sites/default/services.yml is the first step: (note that this is a Drupal 8.4.5 version)

 twig.config: { debug: true, auto_reload: true, cache: false }

Using the Drupal 8 Twig Xdebug Module

Then you could use {{ dump() }} to see all variables that are available but it's very hard to read.
If you have installed Xdebug properly you should use the Twig Xdebug module which is awesome.

You now have an option to see all available twig options in a separate template file that opens when you run Xdebug when using a special tag called {{ breakpoint() }}

{{ breakpoint() }}
  set classes = [
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,

{% set bgColor %}
  {{ content.field_background_color }}
{% endset %}

{% if content.field_full_image %}
  {{ content.field_full_image }}
{% endif %}
Drupal8 Twig Xdebug Screenshot

All fields are available from:
$context["content"], just render {{ content.field_name }}, so replace $context["content"] with {{ content }} 

Happy theming! 🤩

Do you have something useful and positive to say about this article?

Up next: