How to get all assigned Smarty variables while run

2019-05-03 20:02发布

问题:

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?

回答1:

all code below is smarty2

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}


回答2:

You can just assign an array to your smarty variable. Something like this:

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

when you assign this to your template with the name magic_array_of_variables, the exact smarty template you provided should give the output you want



回答3:

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

Like @perikilis described, you can simply register a plugin function to push the result of getTemplateVars() back to the assigned variables list. If you wanted to prevent some data duplication and other weirdness, you might want to only assign the array_keys() and access the actual variables like {${$varname}} (Smarty3).



标签: php smarty