Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to var_dump variables in twig templates?

Tags:

debugging

twig

People also ask

How do you access variables in Twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .

How do I add a global variable in Twig?

If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.

How do you use Kint in Twig?

Kint can also be used in Twig templates. To print a variables, just add {{ kint() }} into the template and pass a variable in, for example, {{ kint(page) }}.


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) }}

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.


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')) }}

So I got it working, partly a bit hackish:

  1. Set twig: debug: 1 in app/config/config.yml
  2. Add this to config_dev.yml

    services:
        debug.twig.extension:
            class: Twig_Extensions_Extension_Debug
            tags: [{ name: 'twig.extension' }]
    
  3. sudo rm -fr app/cache/dev

  4. To use my own debug function instead of print_r(), I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php and changed print_r( to d(

PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.