簡體   English   中英

Smarty中的動態變量名稱

[英]Dynamic variable names in Smarty

我想訪問我在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等因為它們的valus會與之沖突彼此。

鑒於我知道我想根據我設置的content_name訪問標題和正文變量,我怎樣才能在smarty中實現這一點?

根據我對使用數組而不是動態變量的評論,這里是一個如何將變量添加到數組的示例:

PHP:

$vars = array();

function whatever() {
    global $vars;


    $vars[] = array(
        'firstname' => 'Mike',
        'surname' => 'Smith'
    );
}

$smarty->assign('vars', $vars);

智者:

{section name=loop loop=$vars}
    Name: {$vars[loop].firstname} {$vars[loop].surname}
{/section}

即使這篇文章很老,但是給出的回答是有問題的,但不是對這個問題的回答。 它只是處理主要問題的另一個機會。

問題是如何使用動態變量......

對於給定的樣本,它應該是類似的

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

Smarty的

{$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);

Smarty的

{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}}會有效。

對於所有需要它的人,享受吧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM