How to get all assigned Smarty variables while running the template?

血红的双手。 提交于 2019-12-05 13:13:25

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}

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

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!