最近因为个人原因需把项目重制,从而转投到CI的学习中,鉴于CI是一个MVC框架,自学时也看了开发手册,稍微接触了CI的模板引擎,但是用起来却并不怎么好用(例如没法解析数组
在朋友的推荐下,我开始寻找关于CI跟Smarty的整合教程,也感谢HEX大大提供的教程,但由于我使用的是CI3.X版本,几经尝试过此方法都无法实现CI3.X与Smarty3.x的整合,下班到家时就到百度搜寻相关资料,经过半小时左右努力,已经成功的整合了CI3.X与Smarty3.X的整合方式
下面我就给大家详细说明一下配置步骤。
第一步:安装CodeIngiter。 这个不需要详细说,下载地址为:http://codeigniter.com/downloads/
第二步:下载最新版本的 Smarty库,下载地址:http://www.smarty.net/download
第三步:在application/libraries创建smarty文件夹,并将解压好的Smarty库中的libs文件夹复制到Smarty文件夹中
第四步:在application/config下创建smarty.php, 代码如下:
PHP复制代码
<?phpif (!defined('BASEPATH')) { exit('No direct script access allowed');}$config['cache_lifetime'] = 60;$config['caching'] = false;$config['template_dir'] = APPPATH
. 'views/templates';$config['compile_dir'] = APPPATH
. 'views/templates_c';$config['cache_dir'] = APPPATH
. 'views/cache';$config['config_dir'] = APPPATH
. 'views/config';$config['use_sub_dirs'] = false;//子目录变量(是否在缓存文件夹中生成子目录)$config['left_delimiter'] = '{';$config['right_delimiter'] = '}'; 复制代码
第五步:在application/libraries下创建一个Ci_Smarty.php,代码如下:
PHP复制代码
<?phpif (!defined('BASEPATH')) { exit('No direct script access allowed');}require_once APPPATH
.'libraries/smarty/libs/Smarty.class.php';class Ci_Smarty
extends Smarty
{ protected $ci; public function __construct
() { parent
::__construct
(); $this -> ci =& get_instance
(); $this -> ci -> load -> config('smarty'); //加载smarty的配置文件 $this -> cache_lifetime = $this -> ci -> config -> item('cache_lifetime'); $this -> caching = $this -> ci -> config -> item('caching'); $this -> config_dir = $this -> ci -> config -> item('config_dir'); $this -> template_dir = $this -> ci -> config -> item('template_dir'); $this -> compile_dir = $this -> ci -> config -> item('compile_dir'); $this -> cache_dir = $this -> ci -> config -> item('cache_dir'); $this -> use_sub_dirs = $this -> ci -> config -> item('use_sub_dirs'); $this -> left_delimiter = $this -> ci -> config -> item('left_delimiter'); $this -> right_delimiter = $this -> ci -> config -> item('right_delimiter'); }} 复制代码
注意:文件名可以随意保存,但接下来的步骤会用到此文件,所以请区分大小写
第六步:打开application/config/autoload.php 修改:
PHP复制代码
$autoload['libraries'] = array(''); 改为
$autoload['libraries'] = array('Ci_Smarty'); //请注意一点 array里的值请填写第五步所创建的文件名,注意区分大小写,否则CI会提示unload class 复制代码
第六步:在application/core下新建一个MY_Controller.php ,代码如下:
PHP复制代码
<?php
class MY_controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function assign($key, $val)
{
$this->ci_smarty->assign($key, $val);
}
public function display($html)
{
$this->ci_smarty->display($html);
}
}
复制代码
注意:虽然MY_Controller继承CI的控制层,但是在Controller编写代码时 可以直接继承MY_Controller,并且不影响使用CI中自带的libraries以及helper
下面是测试结果:
原文链接:http://codeigniter.org.cn/forums/thread-23745-1-1.html