Search code examples
phptwigsymfony-2.1

array of required twig variables in symfony


If there any way to discover the variables required from a Twig template? Example, if I had:

Hello {{ user }}! You're {{ age }} years old, well done big man!

I'd be able to load this template and then gather each of the required variables, eventually allowing me to have something like:

Array ( [0] => user [1] => age )

The end goal of this is to be able to define a view and then have the system create a form based on the required variables in a template file.


Solution

  • Working Solution

    Thanks to morg for pointing me towards tokenize I was able to get what I wanted using the following (I placed it in my controller for testing):

    $lexer = new \Twig_Lexer(new \Twig_Environment());
    $stream = $lexer->tokenize(new \Twig_Source('{{test|raw}}{{test2|raw|asd}}{{another}}{{help_me}}', null));
    $variables = array();
    while (!$stream->isEOF()) {
        $token = $stream->next();
        if($token->getType() === \Twig_Token::NAME_TYPE){
            $variables[] = $token->getValue();
            while (!$stream->isEOF() && $token->getType() !== \Twig_Token::VAR_END_TYPE) {
                $token = $stream->next();
            }
        }
    }
    $variables = array_unique($variables);
    

    This returns:

    Array
    (
        [0] => test
        [1] => test2
        [2] => another
        [3] => help_me
    )
    

    You'll notice I only get variables and not any of the functions (this is through design), although you could remove the nested while loop if you wish to get both variables and functions.