php – 与Kohana无缝使用模板系统?
我计划在下一个项目中使用Mustache模板和Kohana.所以我要做的是让Kohana在呈现视图时无缝地使用Mustache.例如,我会在我的views文件夹中有这个文件:
myview.mustache 然后我可以在我的应用程序中执行: $view = View::factory('myview'); echo $view->render(); 就像我对常规视图一样. 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)); } } 解决方法
是的你可以.由于Kohana在自动加载方面做了一些诡计,他们称之为“级联文件系统”,你可以有效地重新定义核心类的功能.如果您熟悉,Code Igniter也会这样做.
特别是,这是您所指的View :: factory方法. Source. public static function factory($file = NULL,array $data = NULL) { return new View($file,$data); } 如您所见,这将返回View的一个实例.最初,View没有定义,所以PHP会使用自动加载来寻找它.这时您可以通过定义自己的View类来利用级联文件系统功能,该类必须位于文件APPPATH / View.php中,其中APPPATH是index.php中定义的常量. The specific rules are defined here. 因此,既然我们可以定义自己的View类,那么我们就可以了.具体来说,我们需要覆盖View :: capture,它由$view-> render()调用以捕获模板的包含. 请查看the default implementation,了解可执行的操作和可用内容.我概述了一般的想法. 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); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |