简体   繁体   中英

how to assign an object to smarty templates?

i created a model object in 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?

I know i can do this

$smarty->assign('title', $user->title);

but my object has something like over 20 plus properties.

Please advise.

EDIT 1

the following didn't work for me.

$smarty->assign('user', $user);

OR

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

then i try to {$user->title}

nothing came out.

EDIT 2

I am only currently trying to output the public property of the object in the smarty template. 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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM