[英]how to assign an object to smarty templates?
i created a model object in PHP 我在PHP中创建了模型对象
class User {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
How do i expose the property of a User object in smarty just by assigning the object? 我如何仅通过分配对象来在Smarty中公开用户对象的属性?
I know i can do this 我知道我能做到
$smarty->assign('title', $user->title);
but my object has something like over 20 plus properties. 但是我的对象有20多个属性。
Please advise. 请指教。
EDIT 1 编辑1
the following didn't work for me. 以下对我不起作用。
$smarty->assign('user', $user);
OR 要么
$smarty->register_object('user', $user);
then i try to {$user->title}
然后我尝试{$user->title}
nothing came out. 什么都没出来。
EDIT 2 编辑2
I am only currently trying to output the public property of the object in the smarty template. 我目前仅尝试在smarty模板中输出对象的公共属性。 Sorry if i confused any one with the function. 对不起,如果我混淆任何人的功能。
Thank you. 谢谢。
You should be able to access any public properties of an object from a Smarty template. 您应该能够从Smarty模板访问对象的任何公共属性。 For instance: 例如:
$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'
You can also use assign_by_ref
if you plan on updating the object after assigning it to the Smarty template: 如果您计划在将对象分配给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');
And in the template file 并在模板文件中
{$user2->title} ## Outputs the string 'title #2'
$smarty->assign('user', $user);
在模板中
{$user->title}
This one works for me. 这对我有用。
$smarty->register_object('user', $user);
// Inside the template. note the lack of a $ sign
{user->title}
This one doesn't work regardless whether i have the $ sign 不管我是否有$符号,这都不起作用
$smarty->assign('user', $user);
I hope someone can tell me why. 我希望有人能告诉我原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.