在CakePHP中使用Smarty做为模板系统

来源:互联网 发布:什么值得买源码 编辑:程序博客网 时间:2024/06/11 17:07
由于这次的项目对方客户指定要求用CakePHP,所以只好硬着头皮去学习这个框架,无奈客户还有个要求,就是模板要使用Smarty,这下配置环境成了大问题,网上很多文章都是讲CakePHP 1.1和Smarty的整合的,很少有见1.2的,不过还是找到了方法,使Smarty成为CakePHP的一个组件,这样就完成了整合.
下面是整合的方法:
1.下载1.2版本的CakePHP,放在web目录中.
2.在/vendors目录下建立smarty目录
3.下载新版的Smarty,将解压后的libs目录整个拷贝到/vendors/smarty目录下
4.在/app/controllers/components/下建立新文件,文件名为smarty.php,内容如下:
  1. <?php
  2. vendor('Smarty' . DS . 'libs' . DS . 'Smarty.class');
  3. class SmartyComponent extends Smarty {
  4.         var $controller;
  5.         var $template_dir;
  6.         var $compile_dir;
  7.         var $cache_dir;
  8.         
  9.         function __construct() {
  10.                 parent::__construct();
  11.                 $this->template_dir = VIEWS;
  12.                 $this->compile_dir =  TMP . 'smarty' . DS . 'compile' . DS;
  13.                 $this->cache_dir = TMP . 'smarty' . DS . 'cache' . DS;
  14.                 $this->left_delimiter = '<{';  
  15.                 $this->right_delimiter = '}>';
  16.         }
  17. }
  18. ?>
5.在/app/tmp目录下建立smarty/cache和smarty/compile目录
6.在controller中使用
  1. var $components = array('smarty');
调用smarty,并使用
  1. function render() {}
来防止CakePHP调用本事的view去显示页面.

下面是一个简单的controller的例子
  1. class PostsController extends AppController {
  2.     var $name = 'Posts';
  3.     var $components = array('smarty');
  4.     function index() {
  5.         $this->smarty->caching = true;
  6.         $this->smarty->cache_lifetime = 3600*5;
  7.         $this->smarty->assign('posts'$this->Post->findAll());
  8.         $this->smarty->display('posts/index.tpl');
  9.     }
  10.     function render() {}
  11. }
index.tpl与普通的smarty模板没有任何区别.

如果大家在使用中有任何问题,欢迎与我讨论.