lau*_*ent 4 php template-engine kohana mustache
我计划在下一个项目中使用Mustache模板和Kohana.所以我要做的是让Kohana在渲染视图时无缝地使用Mustache.例如,我会在我的views
文件夹中有这个文件:
myview.mustache
然后我可以在我的应用程序中执行:
$view = View::factory('myview');
echo $view->render();
Run Code Online (Sandbox Code Playgroud)
就像我对常规视图一样.Kohana是否允许这种事情?如果没有,有没有办法我自己使用模块实现它?(如果是这样,最好的方法是什么?)
PS:我看过Kostache但是它使用了自定义语法,对我来说就像直接使用Mustache PHP一样.我希望使用Kohana的语法来做到这一点.
编辑:
根据@ erisco的回答,这就是我最终做到这一点的方式.
完整的模块现在可以在GitHub上获得:Kohana-Mustache
在APPPATH/classes/view.php中:
<?php defined('SYSPATH') or die('No direct script access.');
class View extends Kohana_View {
public function set_filename($file) {
$mustacheFile = Kohana::find_file('views', $file, 'mustache');
// If there's no mustache file by that name, do the default:
if ($mustacheFile === false) return Kohana_View::set_filename($file);
$this->_file = $mustacheFile;
return $this;
}
protected static function capture($kohana_view_filename, array $kohana_view_data) {
$extension = pathinfo($kohana_view_filename, PATHINFO_EXTENSION);
// If it's not a mustache file, do the default:
if ($extension != 'mustache') return Kohana_View::capture($kohana_view_filename, $kohana_view_data);
$m = new Mustache;
$fileContent = file_get_contents($kohana_view_filename);
return $m->render($fileContent, Arr::merge(View::$_global_data, $kohana_view_data));
}
}
Run Code Online (Sandbox Code Playgroud)
是的你可以.由于Kohana在自动加载方面做了一些诡计,他们称之为"级联文件系统",你可以有效地重新定义核心类的功能.如果您熟悉,Code Igniter也会这样做.
特别是,这是您所指的View :: factory方法.来源.
public static function factory($file = NULL, array $data = NULL)
{
return new View($file, $data);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这将返回一个实例View
.最初,View
没有定义,因此PHP会使用自动加载来寻找它.这是当你可以通过定义自己的视图类,这必须是在文件中利用层叠文件系统功能APPPATH/View.php
,其中APPPATH
中定义的常数index.php
.具体规则在此定义.
因此,既然我们可以定义自己的View类,那么我们就可以了.具体来说,我们需要覆盖View::capture
,通过调用$view->render()
来捕获模板的包含.
查看默认实现,以了解要执行的操作和可用的操作.我概述了一般的想法.
class View
{
/**
* 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)
{
// there
$basename = $kohana_view_filename;
// assuming this is a mustache file, construct the full file path
$mustachePath = $some_prefix . $basename . ".mustache";
if (is_file($mustachePath))
{
// the template is a mustache template, so use whatever our custom
// rendering technique is
}
else
{
// it is some other template, use the default
parent::capture($basename, $kohana_view_data);
}
}
}
Run Code Online (Sandbox Code Playgroud)