[英]Kostache - before() method
好吧,kostache模塊中是否有類似before()方法的東西? 例如,如果我在視圖文件中有幾行PHP行,我想在視圖類中分別執行它們,而不回顯模板本身中的任何內容。 我該如何處理?
您可以將這種類型的代碼放入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());
}
}
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.