让Kohana使用第三方模版引擎

php中文网
发布: 2016-07-25 09:10:41
原创
1121人浏览过
Kohana的视图层很简单,变量数据放在$_data数组中。所以继承Kohana_View类并覆写部分方法,就可以非常轻松的使用第三方模版引擎作为视图层。
这里的例子是使用Blitz Template,如果要用Smarty之类的也可以类似修改。
文件在application/classes/stucampus/system/view.php下,可以修改,但是修改要和命名空间对应。至于如何支持命名空间,见 这里
  1. namespace StuCampus\System;
  2. class View extends \Kohana_View
  3. {
  4. /**
  5. * 模版引擎
  6. *
  7. * @var \Blitz
  8. */
  9. protected static $templateEngine = null;
  10. /**
  11. * Returns a new View object. If you do not define the "file" parameter,
  12. * you must call [View::set_filename].
  13. *
  14. * $view = View::factory($file);
  15. *
  16. * @param string view filename
  17. * @param array array of values
  18. * @return View
  19. */
  20. public static function factory($file = NULL, array $data = NULL)
  21. {
  22. return new self($file, $data);
  23. }
  24. /**
  25. * Captures the output that is generated when a view is included.
  26. * The view data will be extracted to make local variables. This method
  27. * is static to prevent object scope resolution.
  28. *
  29. * $output = View::capture($file, $data);
  30. *
  31. * @param string filename
  32. * @param array variables
  33. * @return string
  34. */
  35. protected static function capture($kohana_view_filename, array $kohana_view_data)
  36. {
  37. // 覆写parent
  38. $params = array_merge($kohana_view_data, self::$_global_data);
  39. $output = self::$templateEngine->parse($params);
  40. return $output;
  41. }
  42. /**
  43. * 设置视图的文件名
  44. *
  45. * @example $view->set_filename($file);
  46. *
  47. * @param string view filename
  48. * @return View
  49. * @throws \Kohana_View_Exception
  50. */
  51. public function set_filename($file)
  52. {
  53. $return = parent::set_filename($file);
  54. // 初始化试图引擎
  55. self::$templateEngine = new \Blitz($this->_file);
  56. return $return;
  57. }
  58. /**
  59. * 解析模板
  60. *
  61. * @see Kohana_View::render()
  62. */
  63. public function render($file = NULL)
  64. {
  65. // 这个方法和parent一样的,但是parent没有使用静态延迟绑定,所以只好重写一次= =#
  66. if ($file !== NULL)
  67. {
  68. $this->set_filename($file);
  69. }
  70. if (empty($this->_file))
  71. {
  72. throw new Kohana_View_Exception('You must set the file to use within your view before rendering');
  73. }
  74. // Combine local and global data and capture the output
  75. return View::capture($this->_file, $this->_data);
  76. }
  77. }
复制代码


最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号