How to retrieve all Variables from a Twig Template?

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

    After I spent quite a night, trying all the above answers, I realized, for some unexpected reason, regexps did not work at all with my simple templates. They returned junk or partial information. So I decided to go by erasing all the content between tags instead of counting tags ^_^.

    I mean, if a template is 'AAA {{BB}} CC {{DD}} {{BB}} SS', I just add '}}' in the beginning of the template and '{{ in the end.... and all the content between }} and {{ I'll just strip out, adding comma in between =>}}{{BB,}}{{DD,}}{{BB,}}{{. Then - just erase }} and {{.

    It took me about 15 min to write and test.... but with regexps I've spent about 5 hrs with no success.

    /**
     * deletes ALL the string contents between all the designated characters
     * @param $start - pattern start 
     * @param $end   - pattern end
     * @param $string - input string, 
     * @return mixed - string
     */
     function auxDeleteAllBetween($start, $end, $string) {
        // it helps to assembte comma dilimited strings
        $string = strtr($start. $string . $end, array($start => ','.$start, $end => chr(2)));
        $startPos  = 0;
        $endPos = strlen($string);
        while( $startPos !== false && $endPos !== false){
            $startPos = strpos($string, $start);
            $endPos = strpos($string, $end);
            if ($startPos === false || $endPos === false) {
                return $string;
            }
            $textToDelete = substr($string, $startPos, ($endPos + strlen($end)) - $startPos);
            $string = str_replace($textToDelete, '', $string);
        }
        return $string;
    }
    
    /**
     * This function is intended to replace
     * //preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', 
     * which did not give intended results for some reason.
     *
     * @param $inputTpl
     * @return array
     */
    private function auxGetAllTags($inputTpl){
       $inputTpl = strtr($inputTpl, array('}}' => ','.chr(1), '{{' => chr(2)));
       return explode(',',$this->auxDeleteAllBetween(chr(1),chr(2),$inputTpl));
    }
    
    
    $template = '
    

    Dear {{jedi}},
    New {{padawan}} is waiting for your approval:

    ...'; print_r($this->auxGetAllTags($template));

    Hope it'll help somebody :)

    提交回复
    热议问题
    Register as{{register_as}}, user-{{level}}
    Name{{first_name}} {{last_name}}