175

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Alexander Morland
  • 6,356
  • 7
  • 32
  • 51

15 Answers15

280

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 Symfony.

{{ dump(user) }}
Icode4food
  • 8,504
  • 16
  • 61
  • 93
  • 3
    BTW, be careful when dumping objects with relational mapping – pleerock Nov 04 '13 at 18:33
  • 19
    When I use `{{ dump() }}` to dump all variables, It return a blank page. Is there any other way to dump a variable ? – Jerry Pham Dec 26 '13 at 04:09
  • I'm using latest version of Symfony 2.5, and have the config.yml and config_dev.yml setup and debug mode turned on when loading the kernel for the dev environment. I've tried the other manual methods mentioned by Morland below. Either way, I also get a blank page when dump is used. And no dump. – Chadwick Meyer Oct 01 '14 at 21:37
  • If you get a blank page with and without the `dump`, obviously the `dump` isn't the problem. I would suggest posting a new question if you can't figure it out otherwise. – Icode4food Oct 02 '14 at 13:29
  • @JerryPham Yes, this seems to be a problem. I get a Varnish error when I try to use `{{ dump() }}`, makes no difference turning Varnish off either. – crmpicco Apr 24 '15 at 09:34
  • 3
    I get the following error: ` Twig_Error_Syntax - Unknown "dump" function` – Pathros Sep 21 '16 at 19:18
  • You have to enable dump. See http://twig.sensiolabs.org/doc/functions/dump.html for more information. – MicWit Oct 18 '16 at 01:12
  • strangely, the official symfony's doc still say two ways exists : http://symfony.com/doc/current/components/var_dumper.html#debugbundle-and-twig-integration _{% dump foo.bar %} is the way to go when [...]_ – Bruno Dec 26 '16 at 08:59
  • 5
    A much better approach to look for your full layer of data from twig is described on this link: [how-to-retrieve-all-variables-from-a-twig-template](https://stackoverflow.com/questions/12799094/how-to-retrieve-all-variables-from-a-twig-template) The response that worked for me is ``. Hope this can help – Diego Mello May 27 '21 at 14:54
  • 1
    if `dump()` in Twig is just a blank screen check your server error logs, it's often a memory exhausted issue – James Dec 06 '21 at 03:11
44

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')) }}
redochka
  • 12,345
  • 14
  • 66
  • 79
30

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.

igorw
  • 27,759
  • 5
  • 78
  • 90
  • 7
    If you get a error saying `Unknown tag name "debug"`, extend your configuration (either in the global `config.yml` or `config_dev.yml`) as described here: https://github.com/symfony/symfony-docs/issues/455#issuecomment-1884861 – flu Jan 29 '12 at 14:52
  • 5
    This method is deprecated as of Twig 1.5. – Icode4food Feb 20 '13 at 21:20
  • 4
    Added a deprecation note to the answer. – igorw Feb 20 '13 at 21:51
17

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.

Alexander Morland
  • 6,356
  • 7
  • 32
  • 51
  • 1
    btw: for clearing the cache you can use the console tool (http://stackoverflow.com/questions/6789950/symfony2-how-to-switch-from-dev-to-prod) – Raffael Sep 06 '11 at 11:35
  • is there any advantage to do that? – Alexander Morland Sep 06 '11 at 12:20
  • it's more straightforward ... if you don't know the console tool, I recommend you check it out – Raffael Sep 06 '11 at 13:57
  • 3
    You shouldn't have to set `twig: debug: 1` because it's inheriting this information from your front controller's environment. Otherwise you could end up in uninentionally outputting debug information in your prod environment. As long as you are working in the dev environment it is enabled by default and it's disabled in your prod environment. – flu Jan 29 '12 at 15:00
  • 1
    This is outdated as of Twig 1.5. See other answer: http://stackoverflow.com/a/10080404/107768 – Icode4food May 04 '12 at 21:37
  • probably something has changed in Twig folders structure, 'Twig_Extensions_Extension_Debug' didn't work for me but I've found this class in another Twig lib folder and 'Twig_Extension_Debug' does the job – Zippp Nov 24 '14 at 13:02
15

If you are using Twig in your application as a component you can do this:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

Then in your templates:

{{ my_variable | var_dump }}
Julio
  • 1,903
  • 2
  • 16
  • 19
7

Dump all custom variables:

<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
    {% if key starts with '_' %}
    {% else %}
        <pre style="background: #eee">{{ key }}</pre>
        {{ dump(value) }}
    {% endif %}
{% endfor %}

You can use my plugin which will do that for you (an will nicely format the output):

Twig Dump Bar

kapitalny
  • 310
  • 4
  • 7
5

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

Standalone

This was found on the link provided by icode4food

$twig = new Twig_Environment($loader, array(
    'debug' => true,
    // ...
));
$twig->addExtension(new Twig_Extension_Debug());

Silex

$app->register(new \Silex\Provider\TwigServiceProvider(), array(
    'debug' => true,
    'twig.path' => __DIR__.'/views'
));
Carlton
  • 5,533
  • 4
  • 54
  • 73
4

The complete recipe here for quicker reference (note that all the steps are mandatory):

1) when instantiating Twig, pass the debug option

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2) add the debug extension

$twig->addExtension(new \Twig_Extension_Debug());

3) Use it like @Hazarapet Tunanyan pointed out

{{ dump(MyVar) }}

or

{{ dump() }}

or

{{ dump(MyObject.MyPropertyName) }}
Tudor Ilisoi
  • 2,934
  • 23
  • 25
3

{{ 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.

Anoop
  • 23,044
  • 10
  • 62
  • 76
3

Since Symfony >= 2.6, there is a nice VarDumper component, but it is not used by Twig's dump() function.

To overwrite it, we can create an extension:

In the following implementation, do not forget to replace namespaces.

Fuz/AppBundle/Resources/config/services.yml

parameters:
   # ...
   app.twig.debug_extension.class: Fuz\AppBundle\Twig\Extension\DebugExtension

services:
   # ...
   app.twig.debug_extension:
       class: %app.twig.debug_extension.class%
       arguments: []
       tags:
           - { name: twig.extension }

Fuz/AppBundle/Twig/Extension/DebugExtension.php

<?php

namespace Fuz\AppBundle\Twig\Extension;

class DebugExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array (
              new \Twig_SimpleFunction('dump', array('Symfony\Component\VarDumper\VarDumper', 'dump')),
        );
    }

    public function getName()
    {
        return 'FuzAppBundle:Debug';
    }

}
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
1

You can edit

/vendor/twig/twig/lib/Twig/Extension/Debug.php

and change the var_dump() functions to \Doctrine\Common\Util\Debug::dump()

Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113
1

As most good PHP programmers like to use XDebug to actually step through running code and watch variables change in real-time, using dump() feels like a step back to the bad old days.

That's why I made a Twig Debug extension and put it on Github.

https://github.com/delboy1978uk/twig-debug

composer require delboy1978uk/twig-debug

Then add the extension. If you aren't using Symfony, like this:

<?php

use Del\Twig\DebugExtension;

/** @var $twig Twig_Environment */
$twig->addExtension(new DebugExtension());

If you are, like this in your services YAML config:

twig_debugger:
    class: Del\Twig\DebugExtension
    tags:
        - { name: twig.extension }

Once registered, you can now do this anywhere in a twig template:

{{ breakpoint() }}

Now, you can use XDebug, execution will pause, and you can see all the properties of both the Context and the Environment.

Have fun! :-D

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
1

For debugging Twig templates you can use the debug statement.

enter image description here

There you can set the debug setting explicitely.

Raffael
  • 19,547
  • 15
  • 82
  • 160
  • I get 'Unknown tag name "debug" ' with and without setting that twig.debug: true – Alexander Morland Sep 06 '11 at 10:26
  • if you are working in prod-mode you have to clear the cache first – Raffael Sep 06 '11 at 10:40
  • @AlexanderMorland Hi Alex, you have to extend your configuration as described here: https://github.com/symfony/symfony-docs/issues/455#issuecomment-1884861 to get rid of the `Unknown tag name "debug"` error. – flu Jan 29 '12 at 14:57
0

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() }}
Hazarapet Tunanyan
  • 2,809
  • 26
  • 30
0

{{ variable|debug }} {{ variable|debug('Debug Label Here') }} {{ form.fields|debug_email('Fields') }} {{ dump(variable, variable2, variable3) }} {{ dump() }}

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 10 '23 at 19:06