让Kohana使用第三方模版引擎
Kohana的视图层很简单,变量数据放在$_data数组中。所以继承Kohana_View类并覆写部分方法,就可以非常轻松的使用第三方模版引擎作为视图层。br / 这里的例子是使用Blitz Template,如果要用
Kohana的视图层很简单,变量数据放在$_data数组中。所以继承Kohana_View类并覆写部分方法,就可以非常轻松的使用第三方模版引擎作为视图层。
这里的例子是使用Blitz Template,如果要用Smarty之类的也可以类似修改。
文件在application/classes/stucampus/system/view.php下,可以修改,但是修改要和命名空间对应。至于如何支持命名空间,见 这里
这里的例子是使用Blitz Template,如果要用Smarty之类的也可以类似修改。
文件在application/classes/stucampus/system/view.php下,可以修改,但是修改要和命名空间对应。至于如何支持命名空间,见 这里
<?php
namespace StuCampus\System;
class View extends \Kohana_View
{
/**
* 模版引擎
*
* @var \Blitz
*/
protected static $templateEngine = null;
/**
* Returns a new View object. If you do not define the "file" parameter,
* you must call [View::set_filename].
*
* $view = View::factory($file);
*
* @param string view filename
* @param array array of values
* @return View
*/
public static function factory($file = NULL, array $data = NULL)
{
return new self($file, $data);
}
/**
* Captures the output that is generated when a view is included.
* The view data will be extracted to make local variables. This method
* is static to prevent object scope resolution.
*
* $output = View::capture($file, $data);
*
* @param string filename
* @param array variables
* @return string
*/
protected static function capture($kohana_view_filename, array $kohana_view_data)
{
// 覆写parent
$params = array_merge($kohana_view_data, self::$_global_data);
$output = self::$templateEngine->parse($params);
return $output;
}
/**
* 设置视图的文件名
*
* @example $view->set_filename($file);
*
* @param string view filename
* @return View
* @throws \Kohana_View_Exception
*/
public function set_filename($file)
{
$return = parent::set_filename($file);
// 初始化试图引擎
self::$templateEngine = new \Blitz($this->_file);
return $return;
}
/**
* 解析模板
*
* @see Kohana_View::render()
*/
public function render($file = NULL)
{
// 这个方法和parent一样的,但是parent没有使用静态延迟绑定,所以只好重写一次= =#
if ($file !== NULL)
{
$this->set_filename($file);
}
if (empty($this->_file))
{
throw new Kohana_View_Exception('You must set the file to use within your view before rendering');
}
// Combine local and global data and capture the output
return View::capture($this->_file, $this->_data);
}
}
- 上一篇:PHP微博客应用中的URL缩短类
- 下一篇:一个PHP分页代码,函数形式,返回起始页
精彩图集
精彩文章






