Reputation: 60759
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.
Upvotes: 2
Views: 6120
Reputation: 41
{debug}
I realize this thread is old, but this is the built-in solution.
Upvotes: 1
Reputation: 8459
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);
}
Upvotes: 4
Reputation: 723
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.
Upvotes: -1
Reputation: 75724
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];
Upvotes: 2