2013-03-03 43 views
0

那麼,有沒有像kostache模塊中的before()方法?例如,如果我在視圖文件中有幾條PHP線,我想在視圖類內單獨執行它們,而不在模板本身中回顯任何內容。我該如何處理?Kostache - before()方法

回答

0

您可以將這種類型的代碼放入View類的構造函數中。當視圖被實例化時,代碼將運行。

這是來自工作應用程序的一個(稍作修改)示例。這個例子展示了一個ViewModel,它允許你改變哪個小鬍子文件被用作網站的主佈局。在構造函數中,它會選擇一個默認佈局,如果需要,您可以重寫該佈局。

控制器

class Controller_Pages extends Controller 
{ 
    public function action_show() 
    { 
     $current_page = Model_Page::factory($this->request->param('name')); 

     if ($current_page == NULL) { 
      throw new HTTP_Exception_404('Page not found: :page', 
       array(':page' => $this->request->param('name'))); 
     } 

     $view = new View_Page; 
     $view->page_content = $current_page->Content; 
     $view->title = $current_page->Title; 

     if (isset($current_page->Layout) && $current_page->Layout !== 'default') { 
      $view->setLayout($current_page->Layout); 
     } 

     $this->response->body($view->render()); 
    } 
} 

視圖模型

class View_Page 
{ 
    public $title; 

    public $page_content; 

    public static $default_layout = 'mytemplate'; 
    private $_layout; 

    public function __construct() 
    { 
     $this->_layout = self::$default_layout; 
    } 

    public function setLayout($layout) 
    { 
     $this->_layout = $layout; 
    } 

    public function render($template = null) 
    { 
     if ($this->_layout != null) 
     { 
      $renderer = Kostache_Layout::factory($this->_layout); 
      $this->template_init(); 
     } 
     else 
     { 
      $renderer = Kostache::factory(); 
     } 

     return $renderer->render($this, $template); 
    } 
} 
相關問題