smarty变量--变量范围

你可以选择为主要的Smarty对象作用域分配变量,createData()用来建立数据对象,createTemplate()用来建立模板对象。这些对象支持链式,在模板中可以查看所有模板本身的对象变量和所有分配给父对象链的变量。
默认情况下,模板在执行$smarty->displaty(...)、$smarty->fetch(...)方法时已自动链接至Smarty对象变量范围。
对于分配到单个数据或模板对象的变量,您可以完全控制哪些变量在模板中可见。

这些所谓的主要Smarty对象,共有三个,分别是Smarty、模板、数据;在php程序中,为这些作用域变量赋值时,首先须将它们实例化,如$smarty = New Smarty()、$tpl = createTemplate()、$data = createData()。

例4.6. 变量范围例子

// assign variable to Smarty object scope 为Smarty对象域分配变量
$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 用链接至Smarty对象方式指定模版对象的变量范围
$tpl2 = $smarty->createTemplate('index.tpl',$smarty);
$tpl2->assign('bar','bar-template2');
// This display() does see $foo='smarty' from the $smarty object 在$samrty对象中,执行display(),$foo='smarty'可见
$smarty->display('index.tpl');
// This display() does see $foo='data' and $bar='bar-data' from the data object $data //在数据对象$data中,执行display()令$foo='data'和$bar='bar-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 //数据对象$data执行display(),$foo='data'可见,$bar='bar-data2'在$data2中可见
$smarty->display('index.tpl',$data2);
// This display() does see $bar='bar-template' from the template object $tpl
//模板对象$tpl执行display(),$bar='bar-template'可见
$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);
posted @ 2012-03-08 12:07  haiwei.sun  阅读(495)  评论(0编辑  收藏  举报
返回顶部