CI集成Smarty的实现方式

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

这样集成的目的是什么?html

由于我使用过CI和smarty,因此我就按本身的理解讲一下:CI框架在控制器、models方面作的很好,但在多变的视图方面我感受没有专门处理视图的smarty模板作的好,所以就想到了将这二者合并,各取其长。缓存

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

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

三、在CI的根目录下建立一下文件夹:this

    还有,在CI的helpers文件夹下建立smartyPLU文件夹编码

四、在CI的配置文件夹config下建立smarty.php配置文件,并拷入如下代码:spa

<?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'] = '}>';

五、在CI的libraries文件夹中建立CSmarty.php文件,并拷入如下代码:htm

<?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');
	}
}

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

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

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

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

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

相关文章
相关标签/搜索