跳到内容

变量作用域

你可以选择将变量分配给主 Smarty 对象、使用 createData() 创建的数据对象以及使用 createTemplate() 创建的模板对象的作用域。这些对象可以链接。模板可以看到其自身对象的所用变量及其父对象链中对象分配的所有变量。

默认情况下,由 $smarty->display(...)$smarty->fetch(...) 调用渲染的模板会自动链接到 Smarty 对象变量作用域。

通过将变量分配给单独的数据或模板对象,你可以完全控制模板可以看到哪些变量。

<?php
// assign variable to Smarty object scope
$smarty->assign('foo','smarty');

// assign variables to data object scope
$data = $smarty->createData();
$data->assign('foo','data');
$data->assign('bar','bar-data');

// assign variables to other data object scope
$data2 = $smarty->createData($data);
$data2->assign('bar','bar-data2');

// assign variable to template object scope
$tpl = $smarty->createTemplate('index.tpl');
$tpl->assign('bar','bar-template');

// assign variable to template object scope with link to Smarty object
$tpl2 = $smarty->createTemplate('index.tpl',$smarty);
$tpl2->assign('bar','bar-template2');

// This display() does see $foo='smarty' from the $smarty object
$smarty->display('index.tpl');

// This display() does see $foo='data' and $bar='bar-data' from the data object $data
$smarty->display('index.tpl',$data);

// This display() does see $foo='data' from the data object $data 
// and $bar='bar-data2' from the data object $data2
$smarty->display('index.tpl',$data2);

// This display() does see $bar='bar-template' from the template object $tpl
$tpl->display();  // or $smarty->display($tpl);

// This display() does see $bar='bar-template2' from the template object $tpl2
// and $foo='smarty' form the Smarty object $foo
$tpl2->display();  // or $smarty->display($tpl2);

另请参阅 assign()createData()createTemplate()