2013-03-03 1 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); 
    } 
}