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/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 %}

The variables will only be dumped if Twig's debug setting (in config.yml) is true. By default this means that the variables will be dumped in the dev environment but not the prod environment.

Эта документация является переводом официальной документации Symfony и предоставляется по свободной лицензии CC BY-SA 3.0.