CI集成Smarty的实现方式

给新伙伴的忠告:不要去想着有多复杂,看一遍绝对就会弄了!

这样集成的目的是什么?

因为我使用过CI和smarty,所以我就按自己的理解讲一下:CI框架在控制器、models方面做的很好,但在多变的视图方面我感觉没有专门处理视图的smarty模板做的好,因此就想到了将这两者合并,各取其长。

1、下载CI框架、smarty模板,这个就不需要我多说了。

2、将smarty的libs文件夹copy到CI的third_party文件夹下(其实copy到哪个文件夹下是无所谓的,只要加载到它就行了),并更名为smarty;

3、在CI的根目录下创建一下文件夹:

    还有,在CI的helpers文件夹下创建smartyPLU文件夹

4、在CI的配置文件夹config下创建smarty.php配置文件,并拷入以下代码:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

//指定相关的文件夹
$config['template_dir']    = APPPATH . 'views';
$config['compile_dir']     = FCPATH . 'templates_c';
$config['config_dir']      = FCPATH . 'configs';
$config['cache_dir']       = FCPATH . 'cache';
$config['plugins_dir']     = APPPATH . 'helpers/smartyPLU';

//$config['template_ext']    = ;

//设置缓存,默认为false
$config['caching']         = false;
$config['cache_lifetime']  = 60;

$config['auto_literal']    = false;

$config['left_delimiter']  = '<{';
$config['right_delimiter'] = '}>';

5、在CI的libraries文件夹中创建CSmarty.php文件,并拷入以下代码:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

require_once(APPPATH.'third_party/smarty/Smarty.class.php');     //这里指定Smarty.class.php的存放位置

class CSmarty extends Smarty
{

	protected $CI;

	public function __construct(){

		$this->CI = & get_instance();
		$this->CI->load->config('smarty');       //这里加载smarty的配置信息的文件

		//相关配置项
		$this->template_dir    = $this->CI->config->item('template_dir');
		$this->compile_dir     = $this->CI->config->item('compile_dir');
		$this->config_dir      = $this->CI->config->item('config_dir');
		$this->cache_dir       = $this->CI->config->item('cache_dir');
		$this->plugins_dir     = $this->CI->config->item('plugins_dir');
		//$this->template_ext   = $this->CI->config->item('template_ext');

		$this->caching         = $this->CI->config->item('caching');
		$this->cache_lifetime  = $this->CI->config->item('cache_lifetime');

		$this->auto_literal    = $this->CI->config->item('auto_literal');

        $this->left_delimiter  = $this->CI->config->item('left_delimiter');
        $this->right_delimiter = $this->CI->config->item('right_delimiter');

        //设置编码格式和时区
        header("Content-type:text/html;charset=utf-8");
        date_default_timezone_set('UTC');
	}
}

 6、将smarty的启动加到CI的自启动文件autoload.php文件中:

$autoload['libraries'] = array('CSmarty');

 7、接下来就是在CI中使用了,将CI中的通过$this->load->view("index",$data)方式加载视图改为smarty方式:

$this->csmarty->assign('data', $data);
$this->csmarty->display('index.html');

 PS:使用了smarty的方式时,会出现一些路径上的问题。

posted @ 2015-07-29 11:06  记忆书签  阅读(794)  评论(0编辑  收藏  举报