[英]Kostache - before() method
Well, is there something like before() method in kostache module? 好吧,kostache模块中是否有类似before()方法的东西? 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.
例如,如果我在视图文件中有几行PHP行,我想在视图类中分别执行它们,而不回显模板本身中的任何内容。 How can I handle that?
我该如何处理?
You can put this type of code in the constructor of your View class. 您可以将这种类型的代码放入View类的构造函数中。 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.
本示例说明了一个ViewModel,它使您可以更改将哪个胡须文件用作站点的主要布局。 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 : 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.