简体   繁体   中英

Kostache - before() method

Well, is there something like before() method in kostache module? For example, if I have a couple of PHP lines inside of the view file, I'd like to execute them separately inside of the view class, without echoing anything in the template itself. How can I handle that?

You can put this type of code in the constructor of your View class. When the view is instantiated, the code will run.

Here is a (slightly modified) example from a working application. This example illustrates a ViewModel that lets you change which mustache file is being used as the site's main layout. In the constructor, it chooses a default layout, which you can override if needed.

Controller :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM