Enable Debugging in Twig Templates (Drupal 9)
20 December 2023

Twig is a modern, fast and secure template framework that helps developers in developing new templates and manipulating existing templates effectively. There are lots of differences between the PHP templates and Twig.
Twig has its own syntax and coding standards.
Enabling Twig debugging is much easy in Drupal 9. Twig debugging helps developers easily find template names and theme_suggestions hook to create new template naming structures. Every Drupal 9 site comes with a default.services.yml file in the sites/default directory. Rename it to services.yml.
In that services.yml file there is a parameter called twig.config. Change the debug variable from false to true, But the auto_reload to true, and the cache variable to false are optional. Save and clear the cache.

Step by Step Process To Enable Twig Debugging

There are many ways or options to enable the twig theme debugging.
This is the simplest method. Follow the below steps one by one to enable the twig template debugging by making changes in services.yml:

a) Navigate to /sites/default folder.
b) Copy default.services.yml file and rename it to services.yml.
c) Open the services.yml file and locate 'twig.config'.
d) Set debug to true.

(Note: Set auto_reload to true and cache to false are optional)

e)  Navigate to /sites folder
f) Open development.services.yml file and add the following code

parameters:  
  twig.config:
    debug: true
    auto_reload: true
    cache: false

g) Create a copy of example.settings.local.php file and rename it to settings.local.php
h) Uncomment the following line of code

        $settings['cache']['bins']['render'] = 'cache.backend.null';

I) Open settings.php file and find following code block

if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
include $app_root . '/' . $site_path . '/settings.local.php';
}

j)  Paste it at the bottom of the file.
k) Clear the caches and that’s it.

Now check your browser’s inspector to see all the possible template suggestions in the code as well as which templates are being used.

image

Enabling Twig Debugging With Drupal Console

If you are using the Drupal console then all of this can be done via a single command.
drupal site:mode dev
 
But remember to re-enable prod settings before uploading your site so run
drupal site:mode prod before you upload your site to the server.

kaleem Afridi
Drupal Developer/Drupal Site Builder

Add new comment