开发者

PHP Smarty - Get a list of all the variables in a template?

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

e.g.: 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 in at a later date. Hence I need to be able to get a list of the variables that are in this templates.

Let's assume that I'm only doing simple variables (e.g.: no "{$object.method}" or "{$varaible|function}"), and that I'm not including any other templates.


If you need variables hidden in things like {if $var%2} I'd go with this kind of code :

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

If you also want to catch things like that : {if $var != $var2} a better version follows

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);
}


It looks like there isn't an inbuilt way to do this.


Normally I'm against regular expressions, but this looks like a valid case to me. You could use preg_match_all() to do that (If you only want variables like ${this}):

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


{debug}

I realize this thread is old, but this is the built-in solution.


I think what you're looking for is the debugging console.

This console shows you all variables used within the templates involved in your webpage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜