Issue
Tracing errors or issues according to the Twig template or variable in Drupal 8.
Resolution
There are two main ways of debugging Twig:
- Enable Twig debugging which will help determine which templates are being used.
- Add markup to the page that will allow us to explore the variables available in a template.
Determining template suggestions
Enabling Twig debugging will add markup to the page which tells you information about what templates are being used. The method to debug Twig is briefly outlined on Drupal.org at Debugging Twig templates, which uses a web browser's native debugging tools to aid in finding issues.
Enable Twig debugging in /sites/default/services.yml
file with the following:
parameters: twig.config: debug: true
You then use developer tools with comments enabled to allow viewing information about the template. It may be difficult to find specific documentation on the best practices for using this method.
Debugging Twig variables
Twig supports a way to explore all of the variables available in a template as well as individual variables.
To do this, install the Devel and Kint modules (Kint is included with Devel).
You may need to install the Kint library via Composer: composer require raveren/kint
Then dump all the variables to the screen with a command like this:
{{ kint() }}
Or explore a single variable. Note in this example that you can see the Twig comment format {# comment #}
:
{# Or one variable. #} {{ kint(element) }} {# Or one part of the render array. #} {{ kint(element.hello) }}
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.