gpt4 book ai didi

php - Smarty 中的动态变量名称

转载 作者:搜寻专家 更新时间:2023-10-31 21:18:55 31 4
gpt4 key购买 nike

我想访问一些我在 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com