在Smarty3中,我们可以写包含其他变量的变量名
例如
<?php
$smarty = new Smarty;
$smarty->assign("x",1);
$smarty->assign("foo_1","aka");
$smarty->template_dir = "./";
$smarty->display("tpl.tpl");文件./tpl.tpl内容:
{$foo_{$x}}
<!-- will output aka because foo_1 is assigned as aka -->到目前为止,听起来还不错,但是如果我们使用自定义分隔符,智能引擎就会停止编写包含其他变量的变量。
例如,如果我们使用<--作为左分隔符和-->作为右分隔符
示例
<?php
$smarty = new Smarty;
$smarty->left_delimiter = '<--[';
$smarty->right_delimiter = ']-->';
$smarty->assign("x",1);
$smarty->assign("foo_1","aka");
$smarty->template_dir = "./";
$smarty->display("tpl.tpl");以及当./tpl.tpl文件包含
<--[$foo_<--[$x]-->]--> 错误返回
致命错误: Uncaught > Smarty Compiler:第1行<-- [$foo_<-$x->]
有什么建议吗?
发布于 2014-09-24 14:23:05
经过一番搜索和头痛之后,我找到了解决办法。
看看这个聪明的插件插件http://smarty.incutio.com/?page=VarVar。
它是为Smarty2编写的,我只是将其修改为用于Smarty3的serv
我问题的答案是
<?php
$smarty = new Smarty;
function smarty_modifier_varvar($string) {
global $smarty;
if (empty($string)) {
return;
}
$array = explode(".", $string);
$var = array_shift($array);
$val = $smarty->tpl_vars[$var]->value;
if (count($array) == 0) {
return $val;
} else {
$idx = "['" . join("']['", $array) . "']";
eval("\$return = \$val$idx;");
return $return;
}
}
$smarty->left_delimiter = '<--[';
$smarty->right_delimiter = ']-->';
$smarty->assign("x",1);
$smarty->assign("foo_1","aka");
$smarty->template_dir = "./";
$smarty->display("tpl.tpl");而./tpl.tpl文件是
<--["foo_$x"|varvar]-->由于$foo_1被赋值为aka,所以输出也是aka。
https://stackoverflow.com/questions/26018357
复制相似问题