How to var_dump variables in twig templates?

后端 未结 14 1415
滥情空心
滥情空心 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:33

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

    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';
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题