Twig debug in Symfony 2

Recently I started using Symfony2 with the twig template engine. After the initial phase of adaptation, it’s being very useful to write templates faster, but everything has a downside: I was able to debug php with xDebug in templates, and now I lost that with twig.

So, next thing that comes to mind is the classical var_dump(), which in Twig is symply dump(). But it’s an extension, it does not come activated by default.

As we see in Symfony Documentation, you have to enable the Twig_Extension_Debug as a service in config.yml (or config_dev.yml, of course):

        class:        Twig_Extension_Debug
             - { name: 'twig.extension' }

So, after we do that, you can do a var_dump (Twig uses php’s var_dump internally with the function dump() as follows:

{{ debug(var) }}

and the variable “var” will be dumped. If you call dump() without parameters, Twig will dump all template available variables.

According to documentation, you can enclose the statement between “pre” so output looks more friendly.

{{ debug(var) }}

But, First thing I got was an error. When I tried to dump an array of objects, Twig was crashing and all I saw was a blank page. Note that my each of my objects in the array, had a collection of other objects, which also had a reference to the parent object (Manytoone bidirectional association). I don’t remember why I thought of that, but after a while I tried to remove the inverse side of the association, so the collecion of objects had no reference back.
Doing that, Twig was able to display again the dump of the object, so my guess was that with bidirectional associations, Twig’s dump is not working.

Knowing that now I am more careful using it, but in any other cases I found it working as expected, so at least is a way to see what resources you have available in a Twig template!

(if you know how to overcome this bidirectional association problem, let me know!)

One thought on “Twig debug in Symfony 2

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>