簡體   English   中英

如何將對象分配給smarty模板?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM