Let's Debug Twig in Drupal 8!

Editor's note: This blog post was written during the Drupal 8 development cycle and probably contains out-of-date information. Check out our Drupal 8 Theming Guide for the latest information. In particular, check out Configure Your Environment for Theme Development for more comprehensive information about how to set up your local development environment for theming in Drupal 8, including Twig debugging.

Turn On Twig Debugging

When I am theming a Drupal site, I need to know which variables are available on a template file. In Drupal 8, the template engine is Twig, so we’re going to need to know a little bit of Twig to make this work. So, if Twig is totally new to you, don’t worry. Today, you’ll learn some Twig!

Update and important note! The following instructions work in the alpha version of Drupal 8 only. In the latest development release, the twig_debug settings are no longer in settings.php. It's in sites/example.settings.local.php and the suggestion is to take that file and copy it into sites/default. (Link to change record.) Thanks to Cottser for the heads-up!

The first thing we need to do is to turn on twig debugging. We’ll need to open up sites/default/settings.php to do that. In settings.php, after searching for "Twig" I found the following section on Twig debugging:

/**
 * Twig debugging:
 *
 * When debugging is enabled:
 * - The markup of each Twig template is surrounded by HTML comments that
 *   contain theming information, such as template file name suggestions.
 * - Note that this debugging markup will cause automated tests that directly
 *   check rendered HTML to fail. When running automated tests, 'twig_debug'
 *   should be set to FALSE.
 * - The dump() function can be used in Twig templates to output information
 *   about template variables.
 * - Twig templates are automatically recompiled whenever the source code
 *   changes (see twig_auto_reload below).
 *
 * Note: changes to this setting will only take effect once the cache is
 * cleared.
 *
 * For more information about debugging Twig templates, see
 * <a href="http://drupal.org/node/1906392">http://drupal.org/node/1906392</a>.
 *
 * Not recommended in production environments (Default: FALSE).
 */
# $settings['twig_debug'] = TRUE;

Un-comment* the line that contains the twig_debug setting so that...

# $settings['twig_debug'] = TRUE;

becomes

$settings['twig_debug'] = TRUE;

* Remove the pound (#) sign at the beginning of the line. A pound sign (#) enables you to comment out part of a line in Twig. See Comments in Twig for Template Designers.

Clear That Cache

Now I need to clear the cache. On my Drupal 8 site, I’ll navigate to Configuration > Performance and click the Clear all caches button. While I’m at it, I’ll add this page to my shortcut menu by clicking the star next to the page title, because I haven’t got Drush updated yet. (TODO: Update Drush to a version that supports Drupal 8 on your local.) 

Hack Core (Really)

In this post, I just want to focus on debugging Twig in a local sandbox environment, so instead of spinning up a new theme, I am going to hack core in this tutorial. (I did cringe a little bit at first, if that helps.)

By "hacking core" what I mean is: I’m going to navigate to core/themes/bartik/templates and open up page.html.twig file in my IDE, phpStorm. (But, you can use whatever text editor or IDE you like, preferable one with some Twig support, like autocompleting all those double curly braces. See Twig for Template Designers for a list of IDEs that support Twig.)

Opening core/templates/Bartik/templates/page.html.twig, I can now add my debugging function…but which one? I can't just drop in a php var_dump into a template file anymore.

Introducing the Twig dump() function

Twig has a function called dump() that will, you guessed it, dump all the variables on the page. Now, just so you know, when you try to use dump() on page.html.twig, you’ll probably get a White Screen Of Death (WSOD) because it just takes too much memory to recursively traverse and print all those variables.

But just for starters, let’s say I already know that there’s a variable called breadcrumb that I want to inspect. I'll type this into my page.html.twig file, just below the top comment block. The double curly braces are Twig delimiters, meaning, inside these braces, is Twig. (There's another delimiter and we'll get to that in a moment.)

{{ dump(breadcrumb) }}

Image
Output printed at the top of a Drupal 8 page of a Twig dump function showing typical var_dump.

But if you don't know the names of the array keys of variables (after all, that's what you're trying to find out!) you can put this in your page.html.twig file:

{{ dump(_context|keys) }}

Image
Output of a Twig dump statement showing a var_dump of the variables available on this page.



 

I know what you’re thinking. You’re thinking, "Ew. That’s supposed to be useful? I WANT PRETTY ARRAYS."

Well, so do I, my friends. So do I.

Two Ways to Improve Your Own UX

This information seems important and quite possibly contains data I want to get my hands on, but right now it's neither fun nor easy to read that output. Is there a way I can improve my own developer experience here? The short answer is yes. One method uses your browser's developer tools and the other uses a popular contrib module already beloved by Drupal module developers: Devel.

Inspect that Source for Sanity's Sake

The browser output of the Twig dump() function doesn't appear all that useful at first glance, but take a peek under the hood by choosing Inspect Element from the right/ctrl-click menu in Chrome or Firefox and you'll discover all sorts of useful comments and formatting. You'll see as HTML comments: template name suggestions for each region and a formatted, one-value-per-line array. Simply viewing source in any browser will also give you access to these valuable comments and improved formatting of the dump() output.

Image

 

Using Devel and Kint To Tame Arrays of Doom

Viewing source definitely improved the experience of debugging our Twig template, but there is another option as well, provided by the Drupal contrib community: Devel and Devel Kint modules. I visited the Devel project issue queue, home of such useful variable and array inspecting goodness such as dpm() and krumo, and searched the Devel 8.x issue queue for Twig. I was delighted to discover that as of last week, yes, there is a pretty and even more useful way to debug variables in Twig!

Here's how:

  1. Download the 8.x version of Devel and save it to modules. (Yes, just “modules.” Really.)
  2. In the top menu bar click on Manage to reveal the admin menu then “Extend.”
  3. Search for Devel (optional, but useful).
  4. Enable Devel and Devel Kint.
  5. Click the Save configuration button.

This enables Devel and the Devel Kint modules. “Kint” is a debugging tool that is replacing Krumo. It enables you to hide and show levels of arrays, which is very useful in the land of the Arrays of Doom that we deal with, for better or worse, in Drupal.

Using Kint() to Inspect Arrays and Variables

With these modules enabled, now I can put kint() into my page.html.twig file, NOT get a WSOD, and instead, get a traversable formatted widget for digging into the arrays and variables on this page. With Devel and Kint enabled, I can remove my dump() statements and replace them with:

{{ kint() }}

Image
This is Kint.

Now, if I click the [+] sign, I can drill down into all these nested arrays, sans wall-of-text!

Image
This is Kint expanded.

Function not found?

If you got an error when trying to use kint(), then this bears repeating: you have to have Devel and Devel Kint modules enabled for this function to be available for you to call. Otherwise, you're stuck with dump() for now and you could do clever things described in this comment to make the output more readable.

How to Use Kint to Debug Variables in Twig

But we've got Devel and Kint rolling now, so let's take a look how we can make this tool really work for us.

After you’ve inspected all the variables output with kint(), you might want to narrow down your inspection to just one variable. For a top-most key, I could do this:

{{ kint(page) }}

...to output the page variable.

Image
This is Kint output of page array.

If I wanted to go another level deeper into the page array and output the php equivalent of $page[‘content’], I could do this:

{{ kint(page.content) }}

If things were getting out of hand and I wanted to assign some of these arrays to variables, I could do this:

{%  set pagecontent = page.content %}

(You'll notice that instead of double curly braces, I've used the other Twig delimiting syntax using a curly brace and a percent sign.)

And then using kint(), I could debug my new variable like this:

{{ kint(pagecontent) }}

Or an array inside my pagecontent variable:

{{ kint(pagecontent.bartik_content) }}

Gotcha! Dealing with Special Chars in Array Keys

But what about all those array keys using the pound (#) sign?

{{ kint(page.#show_messages) }}

Image
A website error indicating that the pound sign was an unexpected character and it has choked on it.

Ru-roh. Turns out the pound sign (#) and hypen (-) are special characters, so if those characters are in your variable or array key name, an exception will be caught, as they say, and you'll get a website error.

A Problem That Isn't A Problem

Not a problem, it turns out. All I need to do is switch to a different syntax, the “sub-script” syntax, that actually will likely be familiar to you.

{{ kint(page[‘#show_messages’]) }}

Success!

Now it works!

Image
Output of kint function with successful output of an array key that uses a pound sign.

So, hooray for Devel, Kint, and Inspecting Elements! Now we have a much easier way to navigate debugging tool at our disposal for inspecting variables and arrays in a template file that uses Twig.

Much kudos and thanks to Drupal community members Cottser for the initial patch and moshe weitzman for the timely commit in this Devel 8.x issue that brought Kint functionality to Twig template files: https://drupal.org/node/2218949

Resources:

Happy Twig debugging! Share your tips and tricks using both the dump() and kint() functions in the comments.

Comments

FYI - Looks like the Twig debug settings have now been moved into services.yml (instead of settings.php):

I am still strange that after a lot of heep of try I still unable to figure out how to disable my theme cache while developing a Drupal 8 theme.

Very comprehensive tutorial. Thanks! Drupal 8 sure has a lot of cool features, but it's way harder to work with, compared with 7. Anyway, at least it's responsive out of the box.

How is it best to make sense of this and find what is useful? I am using Kint but what it shows just looks like a wall of nonsense to my eyes.

To better understand the output that Kint is giving you, you might want to check out this tutorial on the Render API: https://drupalize.me/tutorial/render-api-overview?p=2512

Also, for a more up-to-date tutorial on setting up your local environment for theming and debugging, check this new tutorial out: https://drupalize.me/tutorial/configure-your-environment-theme-developm…

Hope this helps!

One thing that helped me a lot with kint is not clicking on the plus sign, but clicking in the middle. The plus sign makes the whole tree open which can crash the browser.

Add new comment

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <code class> <ul type> <ol start type> <li> <dl> <dt> <dd><h3 id> <p>
  • Lines and paragraphs break automatically.

About us

Drupalize.Me is the best resource for learning Drupal online. We have an extensive library covering multiple versions of Drupal and we are the most accurate and up-to-date Drupal resource. Learn more