View layer pattern where you only present what you have been given is fine and all, but how do you know what is available? Is there a \"list all defined variables\" function
As of Twig 1.5, the correct answer is to use the dump function. It is fully documented in the Twig documentation. Here is the documentation to enable this inside Symfony2.
{{ dump(user) }}
{{ dump() }}
doesn't work for me. PHP
chokes. Nesting level too deep I guess.
All you really need to debug
Twig templates if you're using a debugger
is an extension like this.
Then it's just a matter of setting a breakpoint and calling {{ inspect() }}
wherever you need it. You get the same info as with {{ dump() }}
but in your debugger.
you can use dump function and print it like this
{{ dump(MyVar) }}
but there is one nice thing too, if you don't set any argument to dump function, it will print all variables are available, like
{{ dump() }}
You can edit
/vendor/twig/twig/lib/Twig/Extension/Debug.php
and change the var_dump()
functions to \Doctrine\Common\Util\Debug::dump()
If you are using Twig as a standalone component here's some example of how to enable debugging as it's unlikely the dump(variable) function will work straight out of the box
This was found on the link provided by icode4food
$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());
$app->register(new \Silex\Provider\TwigServiceProvider(), array(
'debug' => true,
'twig.path' => __DIR__.'/views'
));
You can use the debug
tag, which is documented here.
{% debug expression.varname %}
Edit: As of Twig 1.5, this has been deprecated and replaced with the new dump
function (note, it's now a function and no longer a tag). See also: The accepted answer above.