How to var_dump variables in twig templates?

后端 未结 14 1413
滥情空心
滥情空心 2020-12-22 17:43

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

相关标签:
14条回答
  • 2020-12-22 18:07

    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) }}
    
    0 讨论(0)
  • 2020-12-22 18:08

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

    0 讨论(0)
  • 2020-12-22 18:09

    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() }}
    
    0 讨论(0)
  • 2020-12-22 18:10

    You can edit

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

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

    0 讨论(0)
  • 2020-12-22 18:13

    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'
    ));
    
    0 讨论(0)
  • 2020-12-22 18:16

    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.

    0 讨论(0)
提交回复
热议问题