How to retrieve all Variables from a Twig Template?

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

    I think 19Gerhard85's answer is pretty good, although it might need some tweaking because it matched some empty strings for me. I like using existing functions where possible and this is an approach mostly using twig's functions. You need access to your application's twig environment.

    /**
     * @param $twigTemplateName
     * @return array
     */
    public function getRequiredKeys($twigTemplateName)
    {
        $twig = $this->twig;
        $source = $twig->getLoader()->getSource($twigTemplateName);
        $tokens = $twig->tokenize($source);
        $parsed = $twig->getParser()->parse($tokens);
        $collected = [];
        $this->collectNodes($parsed, $collected);
    
        return array_keys($collected);
    }
    

    And the only custom part of it is the recursive function to collect only certain types of nodes:

    /**
     * @param \Twig_Node[] $nodes
     * @param array $collected
     */
    private function collectNodes($nodes, array &$collected)
    {
        foreach ($nodes as $node) {
            $childNodes = $node->getIterator()->getArrayCopy();
            if (!empty($childNodes)) {
                $this->collectNodes($childNodes, $collected); // recursion
            } elseif ($node instanceof \Twig_Node_Expression_Name) {
                $name = $node->getAttribute('name');
                $collected[$name] = $node; // ensure unique values
            }
        }
    }
    

提交回复
热议问题