How to get all assigned Smarty variables when starting a template?

I would like to get all the variables assigned by Smarty inside the template. For example, if I have this code

$smarty->assign('name', 'Fulano'); $smarty->assign('age', '22'); $result = $this->smarty->fetch("file:my.tpl"); 

I would like to have my.tpl as shown below:

 {foreach from=$magic_array_of_variables key=varname item=varvalue} {$varname} is {$varvalue} {/foreach} 

for example, the content of the result will be

 name is Fulano age is 22 

So, is there a way to get this $magic_array_of_variables ?

+4
source share
3 answers

all code below is smarty2

All smarty variables are stored inside the $ smarty → _ tpl_vars object, so before retrieving () your template, you can:

 $smarty->assign('magic_array_of_variables', $smarty->_tpl_vars); 

Since this can be impractical, you can also write a small smarty plugin function that does something like this:

 function smarty_function_magic_array_of_variables($params, &$smarty) { foreach($smarty->_tpl_vars as $key=>$value) { echo "$key is $value<br>"; } } 

and from your tpl call it with:

 {magic_array_of_variables} 

Alternatively, in this function you can:

 function smarty_function_magic_array_of_variables($params, &$smarty) { $smarty->_tpl_vars['magic_array_of_variables'] = $smarty->_tpl_vars; } 

and in your template:

 {magic_array_of_variables} {foreach from=$magic_array_of_variables key=varname item=varvalue} {$varname} is {$varvalue} {/foreach} 
+6
source

You can simply assign an array to your flexible variable. Something like that:

 $array = array('name' => 'Fulano', 'age' => '22'); 

when you assign this to your template called magic_array_of_variables , then you must specify the exact smarty template you want

+1
source

There is no native way to iterate over assigned variables. However, getTemplateVars () returns an associative array of all assigned values.

As described in @perikilis, you can simply register the plugin function to return the result of getTemplateVars () back to the list of assigned variables. If you want to prevent data duplication and other oddities, you may need to assign array_keys () and access the actual variables like {${$varname}} (Smarty3).

+1
source

All Articles