How to retrieve all Variables from a Twig Template?

前端 未结 14 1475
抹茶落季
抹茶落季 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:05

    $loader1 = new Twig_Loader_Array([
        'blub.html' => '{{ twig.template.code }}',
    ]);
    $twig = new Twig_Environment($loader1);
    $tokens = $twig->tokenize($loader1->getSource('blub.html'));
    $nodes = $twig->getParser()->parse($tokens);
    
    var_dump($this->getTwigVariableNames($nodes));
    
    
    function getTwigVariableNames($nodes): array
    {
        $variables = [];
        foreach ($nodes as $node) {
            if ($node instanceof \Twig_Node_Expression_Name) {
                $name = $node->getAttribute('name');
                $variables[$name] = $name;
            } elseif ($node instanceof \Twig_Node_Expression_Constant && $nodes instanceof \Twig_Node_Expression_GetAttr) {
                $value = $node->getAttribute('value');
                if (!empty($value) && is_string($value)) {
                    $variables[$value] = $value;
                }
            } elseif ($node instanceof \Twig_Node_Expression_GetAttr) {
                $path = implode('.', $this->getTwigVariableNames($node));
                if (!empty($path)) {
                    $variables[$path] = $path;
                }
            } elseif ($node instanceof \Twig_Node) {
                $variables += $this->getTwigVariableNames($node);
            }
        }
        return $variables;
    }
    

    have fun :-)

提交回复
热议问题