[英]how to assign an object to smarty templates?
我在PHP中创建了模型对象
class User {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
我如何仅通过分配对象来在Smarty中公开用户对象的属性?
我知道我能做到
$smarty->assign('title', $user->title);
但是我的对象有20多个属性。
请指教。
编辑1
以下对我不起作用。
$smarty->assign('user', $user);
要么
$smarty->register_object('user', $user);
然后我尝试{$user->title}
什么都没出来。
编辑2
我目前仅尝试在smarty模板中输出对象的公共属性。 对不起,如果我混淆任何人的功能。
谢谢。
您应该能够从Smarty模板访问对象的任何公共属性。 例如:
$o2= new stdclass;
$o2->myvar= 'abc';
$smarty->assign('o2', $o2);
### later on, in a Smarty template file ###
{$o2->myvar} ### This will output the string 'abc'
如果您计划在将对象分配给Smarty模板后更新对象,则也可以使用assign_by_ref
:
class User2 {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
$user2= new User2();
$smarty->assign_by_ref('user2', $user2);
$user2->changeTitle('title #2');
并在模板文件中
{$user2->title} ## Outputs the string 'title #2'
$smarty->assign('user', $user);
在模板中
{$user->title}
这对我有用。
$smarty->register_object('user', $user);
// Inside the template. note the lack of a $ sign
{user->title}
不管我是否有$符号,这都不起作用
$smarty->assign('user', $user);
我希望有人能告诉我原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.