Debugging Twig templates in Drupal 8 Kint

Mon, 02/22/2016 - 08:45 | 1920 Views

One of the most frequent task in development for Drupal is debugging elements that are about to be printed, the most fundamental method to get the debug values is using functions print and print_r

However, with the arrival of Drupal 8 everything change and the usage of that functions is not possible. To resolve that problem with could use the implementation of Kint in Drupal 8.

1. Installing Kint

Using the project Drupal Console, we will download and enable Kint module. Kint module implementation is a submodule of devel module.

Let me show you how to do that with Drupal Console.

$ drupal module:download devel --latest
$ drupal module:install kint 

2. Enabling twig debug

Before to try to use Kint in our templates, we need to disable the twig cache, which is the default status in a Drupal installation, to facilitate that process we will use the Drupal Console project again as you can see below.

$ chmod 755 sites/default/
$ drupal site:mode dev

3. Debugging twig templates.

For example purpose, I will use the Bartik theme included in Drupal 8 core. Editing the file located at core/themes/bartik/templates/page.html.twig adding the following instruction before page wrapper.

{{ kint(page) }}

As a result we will see at the top of the page a Kint section will all information of page but collapsed.

Kint collapsed

It's possible to see the full list clicking in [+] symbol to toggle the JS render for page object.


Kind expanded

It's necessary to remark that Kint is not a PHP function, it's a Twig function, so please don't try to use other PHP function in your twig template, because those function can't be interpreted.

I hope do you find this article useful.