How to Dump Debug Information in Twig Templates

How to Dump Debug Information in Twig Templates

When using PHP, you can use the dump() function from the VarDumper component if you need to quickly find the value of a variable passed. This is useful, for example, inside your controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// src/Controller/ArticleController.php
namespace App\Controller;

// ...

class ArticleController extends Controller
{
    public function recentListAction()
    {
        $articles = ...;
        dump($articles);

        // ...
    }
}

Note

The output of the dump() function is then rendered in the web developer toolbar.

The same mechanism can be used in Twig templates thanks to dump() function:

1
2
3
4
5
6
7
8
{# templates/article/recent_list.html.twig #}
{{ dump(articles) }}

{% for article in articles %}
    <a href="/article/{{ article.slug }}">
        {{ article.title }}
    </a>
{% endfor %}

By design, the dump() function is only available if the kernel.debug setting (in config.yml) is true, to avoid leaking sensitive information in production. In fact, trying to use the dump() function when kernel.debug is false (for example in the prod environment) will result in an application error.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.