Dump Twig template variables with Javascript

Dump Twig template variables with Javascript

Dumping template variables is frustrating

If you have ever worked with Symfony, Drupal or any project that uses Twig as template engine, you might get frustrated at debugging and dumping template variables.

Generally speaking, when working with PHP, the preferable way of debugging would be using the Xdebug extension with some IDEs or editors that offer good support such as PHPStorm, VSCode etc...

If you managed to get Xdebug working then my recommendation is to use it in combination with some module (Twig Xdebug for Drupal) or extension (Breakpoint Twig Extension for Symfony) that allows to set breakpoints.  

On the other hand, if you cannot get Xdebug setup, chances are that you end up using Kint, Twig vardumper or similars. The problem with those is that they might lock up your browser when the rendering gets big.

Dump with console.log()

As alternative, I often dump PHP variables using Javascript console.log() and inspect their value with the web console of the browser.

For instance, say you want to dump _context (reference to the current context which contains all variables passed to the template) in the template node.html.twig; all we need to do is logging our variable as JSON object.

Here is how this can be done:


<script> console.log({{ _context | json_encode | raw }}) </script>

Note we need to apply the filters json_encode which returns the JSON representation of the PHP variable and raw that prevent the variable from being escaped.

This allows us to take advantage of the web console and inspect our PHP variables through the browser dev tools.

Dump Twig template variables with Javascript

Final thoughts

Although this alternative way of dumping variables is thought for Twig, it can actually be used in any template engine as long as we can convert the variables into JSON objects.