PHP Smarty - get a list of all variables in a template?

I am using Smarty and PHP. If I have a template (either as a file or as a string), is there some way I can get smarty to parse that file / string and return an array with all smarty variables in that template?

For example: I want something like this:

$mystring = "Hello {$name}. How are you on this fine {$dayofweek} morning";
$vars = $smarty->magically_parse( $string );
// $vars should now be array( "name", "dayofweek" );

      

The reason I want to do this is because I want users to be able to enter templates themselves and then fill them out later. Hence, I need to be able to get a list of the variables that are in these templates.

Let's assume that I only execute simple variables (ex: no "{$ object.method}" or "{$ varaible | function}"), and that I do not include any other templates.

+2


source to share


5 answers


It looks like there is no built-in way to do this.



+3


source


If you want variables hidden in things like {if $var%2}

, I would go with code like this:

preg_match_all('`{[^\\$]*\\$([a-zA-Z0-9]+)[^\\}]*}`', $string, $result);
$vars = $result[1];

      



If you also want to catch things like this: the {if $var != $var2}

best version should be

function getSmartyVars($string){
  // regexp
  $fullPattern = '`{[^\\$]*\\$([a-zA-Z0-9]+)[^\\}]*}`';
  $separateVars = '`[^\\$]*\\$([a-zA-Z0-9]+)`';

  $smartyVars = array();
  // We start by extracting all the {} with var embedded
  if(!preg_match_all($fullPattern, $string, $results)){
    return $smartyVars;
  }
  // Then we extract all smarty variables
  foreach($results[0] AS $result){
    if(preg_match_all($separateVars, $result, $matches)){
      $smartyVars = array_merge($smartyVars, $matches[1]);
    }
  }
  return array_unique($smartyVars);
}

      

+4


source


Usually I am against regex, but it looks like a valid case to me. You can use preg_match_all()

for this (if you only want type variables ${this}

):

preg_match_all('\{\$(.*?)\}', $string, $matches, PREG_PATTERN_ORDER);
$variableNames = $matches[1];

      

+2


source


{debug}

      

I understand this thread is out of date, but this is a built-in solution.

+1


source


I think you are looking for a debug console .

This console shows all the variables used in templates participating in your web page.

0


source







All Articles