I would like to get all variables assigned to 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 a my.tpl
like the one below:
{foreach from=$magic_array_of_variables key=varname item=varvalue}
{$varname} is {$varvalue}
{/foreach}
such as the content of result would be
name is Fulano
age is 22
So, is there a way to get this $magic_array_of_variables
?
All smarty variables are held inside the $smarty->_tpl_vars object, so before fetching() your template, you could do:
$smarty->assign('magic_array_of_variables', $smarty->_tpl_vars);
Since this may be impractical, you could also write a small smarty plugin function that does something similar:
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 do:
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With