assign()
向模板分配变量/对象
描述
void
assign
mixed
var
void
assign
string
varname
mixed
var
bool
nocache
你可以明确传递名称/值对,或包含名称/值对的关联数组。
如果你传递了可选的第三个参数 nocache 为 TRUE,那么变量将作为非缓存变量分配。详情请参见变量的可缓存性。
注意
当你向模板分配/注册对象时,请确保从模板访问的所有属性和方法仅用于展示目的。通过对象很容易注入应用逻辑,这会导致难以管理的糟糕设计。请参阅 Smarty 网站的最佳实践部分。
<?php
// 传递名称/值对
$smarty->assign('Name', 'Fred');
$smarty->assign('Address', $address);
// 传递关联数组
$smarty->assign(array('city' => 'Lincoln', 'state' => 'Nebraska'));
// 传递数组
$myArray = array('no' => 10, 'label' => 'Peanuts');
$smarty->assign('foo',$myArray);
// 传递数据库中的一行(例如 adodb)
$sql = 'select id, name, email from contacts where contact ='.$id;
$smarty->assign('contact', $db->getRow($sql));
?>
在模板中可以这样访问
{* 注意变量是区分大小写的,就像php一样 *}
{$Name}
{$Address}
{$city}
{$state}
{$foo.no}, {$foo.label}
{$contact.id}, {$contact.name},{$contact.email}
要访问更复杂的数组分配,请参见
{foreach} 和
{section}
另见 assignByRef()、
getTemplateVars()、
clearAssign()、append() 和
{assign}