How to var_dump variables in twig templates?
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" functionality in TWIG? Is there a way to dump a variable?
The solution I found by searching for it was to define a function where I can use my existing php debug tools by injecting a function, but all references I have found to that includes these nice two lines of code, but nowhere is it specified where to place them. Going by the fact that they need a $loader variable defined, I tried /app/config/autoload.php but the $loader there was the wrong kind. Where do I place the php code for adding a twig function?
Solution 1:
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) }}
Solution 2:
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.
Solution 3:
If you are in an environment where you can't use the dump
function (ex: opencart), you can try:
{{ my_variable | json_encode(constant('JSON_PRETTY_PRINT')) }}
Solution 4:
So I got it working, partly a bit hackish:
- Set
twig: debug: 1
inapp/config/config.yml
-
Add this to config_dev.yml
services: debug.twig.extension: class: Twig_Extensions_Extension_Debug tags: [{ name: 'twig.extension' }]
sudo rm -fr app/cache/dev
- To use my own debug function instead of
print_r()
, I openedvendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php
and changedprint_r(
tod(
PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.