CodeIgniter(CI) 是一个小巧但功能强大的 PHP 框架,是一个简单而“优雅”的工具包,是进口的哦,可是他默认没有静态模板引擎,而smarty模板引擎是个很是优秀的模板引擎,拥有很是多的用户,许多开发者都熟悉他。这里就讲讲怎么在CI框架下添加smarty类,来使用smarty模板引擎。php
1.下载smarty,官网:http://www.smarty.net/download.php
把smarty的函数库(libs文件夹)解压放到ci框架下的application文件夹下的libraries里,/applicaton/libraries/smarty/缓存
2.在根目录下的index.php里加入下面一句:app
define('APPNAME', 'application');
3.在smarty文件夹里建cache、templates_c、configs文件夹(模板引擎的放缓存的文件夹,也能够放在其余地方,但要注意下一步SmartyExtended.php里作相应的修改)框架
4.在/application/libraries/下建smarty类文件SmartyExtended.php
SmartyExtended.php(代码)ide
<!--p if (!defined('BASEPATH')) exit('No direct script access allowed'); define('SMARTY_DIR', BASEPATH . '../' . APPNAME . '/libraries/smarty/'); require(SMARTY_DIR . 'Smarty.class.php'); class SmartyExtended extends Smarty { var $CI; var $lang_code; /** * Constructor * * Loads the smarty class * * @access public */ function SmartyExtended() { if (!file_exists(BASEPATH . '../' . APPNAME . '/libraries/smarty/cache')) { mkdir(BASEPATH . '../' . APPNAME . '/libraries/smarty/cache', 0777); } $thi-->CI =& get_instance(); $this->lang_code = $this->CI->config->item('lang_code'); $this->template_dir = BASEPATH . '../' . APPNAME . '/views/'; $this->compile_dir = BASEPATH . '../' . APPNAME . '/libraries/smarty/templates_c/'; $this->config_dir = BASEPATH . '../' . APPNAME . '/libraries/smarty/configs/'; $this->cache_dir = BASEPATH . '../' . APPNAME . '/libraries/smarty/cache/'; $this->caching = true; $this->force_compile = true; log_message('debug', "SmartyExtended Class Initialized"); } function view($template, $data='') { if(trim($data)!='') { if(is_array($data)) { foreach($data as $key=>$val) { $this->assign($key, $val); } } } $this->display($template . '.tpl'); //模板后缀名 } } ?>
5.添加自动调用:
修改/application/config/下的autoload.php函数
$autoload['libraries'] = array('SmartyExtended');
6.调用:
在controller里使用下面方法调用就能够了。工具
$data = array();//initialize array $data['test'] = ......; $this->smartyextended->view('home', $data);
7.在模板里的调用方法参考smarty手册post