代码之家  ›  专栏  ›  技术社区  ›  Kim Stacks

如何将对象分配给智能模板?

  •  1
  • Kim Stacks  · 技术社区  · 16 年前

    我用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模板中输出对象的公共属性。对不起,如果我把任何一个与功能混淆了。

    谢谢您。

    3 回复  |  直到 16 年前
        1
  •  9
  •   leepowers    16 年前

    您应该能够从智能模板访问对象的任何公共属性。例如:

    $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'
    

    您也可以使用 assign_by_ref 如果计划在将对象分配给Smarty模板后更新该对象:

    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'
    
        2
  •  2
  •   Sinan    16 年前
    $smarty->assign('user', $user);
    

    在模板中

    {$user->title}
    
        3
  •  1
  •   Kim Stacks    16 年前

    这个对我有用。

    $smarty->register_object('user', $user);
    
    // Inside the template. note the lack of a $ sign
    {user->title}
    

    不管我有没有美元符号,这个都不行

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

    我希望有人能告诉我原因。