0

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

4

1 回答 1

0

您可以将此类代码放在 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());
    }
}

视图模型

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 回答