Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 3.2 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Dump Debug Information in Twig Templates

3.2 version
Maintained Unmaintained

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:

// src/AppBundle/Controller/ArticleController.php
namespace AppBundle\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
{# app/Resources/views/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.