0

さて、kostacheモジュールにbefore()メソッドみたいなものはありますか?たとえば、ビュー ファイル内に 2 つの PHP 行がある場合、ビュー クラス内でそれらを個別に実行し、テンプレート自体に何もエコーしないようにしたいと考えています。どうすればそれを処理できますか?

4

1 に答える 1

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);
    }
}
于 2013-03-14T20:11:22.570 に答える