0
那么,有没有像kostache模块中的before()方法?例如,如果我在视图文件中有几条PHP线,我想在视图类内单独执行它们,而不在模板本身中回显任何内容。我该如何处理?Kostache - before()方法
那么,有没有像kostache模块中的before()方法?例如,如果我在视图文件中有几条PHP线,我想在视图类内单独执行它们,而不在模板本身中回显任何内容。我该如何处理?Kostache - before()方法
您可以将这种类型的代码放入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);
}
}