Kostache - before() method



那么,在kostache模块中是否有类似before()方法的东西?例如,如果我在视图文件中有几行PHP代码,我希望在视图类中单独执行它们,而不回显模板本身中的任何内容。我该怎么做呢?

您可以将这类代码放入View类的构造函数中。当视图被实例化时,代码将运行。

下面是一个来自工作应用程序的(稍作修改的)示例。这个例子演示了一个ViewModel,它允许您更改使用哪个mustache文件作为站点的主布局。在构造函数中,它选择了一个默认的布局,如果需要,您可以覆盖它。

控制器

:

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());
    }
}

ViewModel :

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);
    }
}

相关内容

最新更新