我想在模板中将所有变量分配给Smarty.例如,如果我有这个代码
$smarty->assign('name', 'Fulano');
$smarty->assign('age', '22');
$result = $this->smarty->fetch("file:my.tpl");
Run Code Online (Sandbox Code Playgroud)
我想有一个my.tpl像下面这样的:
{foreach from=$magic_array_of_variables key=varname item=varvalue}
{$varname} is {$varvalue}
{/foreach}
Run Code Online (Sandbox Code Playgroud)
比如结果的内容就是
name is Fulano
age is 22
Run Code Online (Sandbox Code Playgroud)
那么,有没有办法得到这个$magic_array_of_variables?
所有智能变量都保存在$ smarty - > _ tpl_vars对象中,因此在获取()模板之前,您可以执行以下操作:
$smarty->assign('magic_array_of_variables', $smarty->_tpl_vars);
Run Code Online (Sandbox Code Playgroud)
由于这可能不切实际,您还可以编写一个小巧的插件函数,它可以执行类似的操作:
function smarty_function_magic_array_of_variables($params, &$smarty) {
foreach($smarty->_tpl_vars as $key=>$value) {
echo "$key is $value<br>";
}
}
Run Code Online (Sandbox Code Playgroud)
从你的tpl调用它:
{magic_array_of_variables}
Run Code Online (Sandbox Code Playgroud)
或者,在此功能中,您可以:
function smarty_function_magic_array_of_variables($params, &$smarty) {
$smarty->_tpl_vars['magic_array_of_variables'] = $smarty->_tpl_vars;
}
Run Code Online (Sandbox Code Playgroud)
并在您的模板中:
{magic_array_of_variables}
{foreach from=$magic_array_of_variables key=varname item=varvalue}
{$varname} is {$varvalue}
{/foreach}
Run Code Online (Sandbox Code Playgroud)