How to retrieve all Variables from a Twig Template?

前端 未结 14 1370
抹茶落季
抹茶落季 2020-12-08 00:24

Is it possible to retrieve all variables inside a Twig template with PHP?

Example someTemplate.twig.php:

Hello {{ name }}, 
your new email is {{ ema         


        
相关标签:
14条回答
  • 2020-12-08 01:11

    Here is the best way and easiest way to dump all variables :

    {{ dump () }}
    

    Source : https://www.drupal.org/docs/8/theming/twig/discovering-and-inspecting-variables-in-twig-templates

    0 讨论(0)
  • 2020-12-08 01:17

    You have to parse the template, and walk through the AST it returns:

    $loaded = $twig->getLoader()->getSource($template);
    var_dump(extractVars($twig->parse($twig->tokenize($loaded))));
    
    function extractVars($node)
    {
        if (!$node instanceof Traversable) return array();
    
        $vars = array();
        foreach ($node as $cur)
        {
            if (get_class($cur) != 'Twig_Node_Expression_Name')
            {
                $vars = array_merge($vars, call_user_func(__FUNCTION__, $cur));
            }
            else if ($cur->getAttribute('always_defined') == false)
            {
                // List only predefined variables expected by template, 
                // filtering out `v` and leaving `arr` from `{% for v in arr%}`
                $vars[] = $cur->getAttribute('name');
            }
        }
    
        return $vars;
    }
    
    0 讨论(0)
提交回复
热议问题