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 %}

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:

Drupal 8 form styling

February 16th, 2018

Styling forms in Drupal 8 has changed a bit since Drupal 7 🤯. For instance, if you'd want to alter a form you now use the YOURTHEMENAME.theme file instead of the old template.php file. For reference see:

In this example I'd like to create a contact form (from core, admin/structure/contact/add) and call it contact.

You can now override that form by using the hook_form_FORM_ID_alter() function. The form id of this specific form would be "contact_message_contact_form" so I use a form alter to overwrite the form. 

The form id can be found by using xdebug or by using kint() or devel, using the (more generic) hook_form_alter function