php - Smarty 中的动态变量名称

标签 php smarty dynamic-variables

我想访问一些我在 Smarty 中从 PHP 动态分配的变量,这里是一个例子:

$content_name = 'body'
$smarty->assign('content_name',$content_name);
$smarty->assign($content_name.'_title',$title);
$smarty->assign($content_name.'_body',$body);

// assigned values
// $content_name = home
// $home_title = $title
// $home_body = $body

我想动态访问这些的原因是因为我调用了包含上述代码的函数的多个版本,它们都使用相同的模板,因此不想简单地使用 $title、$body 等作为它们的值会互相冲突。

鉴于我知道我想根据我设置的 content_name 访问 title 和 body 变量,我如何在 smarty 中实现这一点?

最佳答案

即使这篇文章很旧,给定的答案也被接受但不是问题的答案。它只是处理主要问题的另一个机会。

问题是如何使用动态变量...

对于给定的样本,它应该是这样的

PHP

$content_name = 'body';
$title        = 'hello ';
$body         = 'world';
$smarty->assign('content_name',$content_name);
$smarty->assign($content_name.'_title',$title);
$smarty->assign($content_name.'_body',$body);

聪明

{$content_name}          //body
{${$content_name}_title} //hello
{${$content_name}_body}  //world

{${$content_name}_title}{${$content_name}_body} my {$content_name} is awesome
//hello world my body is awesome

这是使用它的动态方式。即使在这种情况下这不是最好的方法 :)

如果你有某种对象或多维数组......并且你喜欢迭代它们,你必须关心整个字符串而不仅仅是数字......

例如:

PHP

$arr = [
    "attr1" => "hello ",
    "attr2" => "world ",
    "attr3" => "my body is awesome"
];
$smarty->assign('foobar', $arr);

聪明

{for $i=1 to 3}
    {$foobar.{"attr$i"}}   //works (whole name must be string var mix)
    //{$foobar.attr{"$i"}} //fails
    //{$foobar.attr{$i}}   //fails
{/for}

但是在一个简单的数组上使用 {$foobar{$i}} 是可行的。

对于所有需要它的人,请享用。

关于php - Smarty 中的动态变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128108/

相关文章:

PHP - 激活进程的多个实例

php - 将 pdf 与 zendpdf 合并

php - 聪明的foreach循环

php - 在 PHP Smarty 模板引擎上禁用缓存?

matlab - 在第二级结构中赋值

php - 具有未知数量参数的方法可以调用另一个具有未知数量参数的方法吗?

php - 将标准 WooCommerce 产品小部件添加到博客文章时出错

php - smarty 不应该解析 javascript 文件

php - 在 PHP 中使用动态变量创建新对象