开发者

Pass php object to smarty

I have an issue with passing an object to smarty tag. I have the following code:

$contact = new Contacts;
$smarty = new Smarty;
$smarty->assign('contact',$contact);

In test.htpl :

<html>
<head>
    <title>{$title}</title>
</head>
<body>
    id: {$contact->id} <br/>
    name: {$contact->name} <br/>
    email: {$contact->email} <br/开发者_StackOverflow中文版>
    phone: {$contact->phone} <br/>
</body>
</html>

this leads to an warning of invalid character '>'. How can I solve this?

I used this class for testing:

class Contacts
{
 public $id = 1;
 public $name = 'Mada';
 public $email = 'mada@yahoo.com';
 public $phone = 123456;
}


Use

$smarty->assign_by_ref('contact',$contact);

This will allow you to access in the way you expect.

Using register_object() is also an option, and allows you to restrict what can be used from the template, but this means a different template format (no initial $).


By doing the following should work

$smarty->register_object('contact',$contact);

Calling it this way should then work

<html>
<head>
    <title>{$title}</title>
</head>
<body>
    id: {$contact->id} <br/>
    name: {$contact->name} <br/>
    email: {$contact->email} <br/>
    phone: {$contact->phone} <br/>
</body>
</html>

Also then you don't need to call this method

$smarty->assign('contact',$contact);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜