嗯,kostache模块中有类似before()方法吗?例如,如果我在视图文件中有几个PHP行,我想在视图类中单独执行它们,而不回显模板本身中的任何内容。我该怎么处理?
答案 0 :(得分: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);
}
}