Ci框架整合smarty模板引擎php
備註:下載smarty時,最好選擇2.6版本,其餘測試有坑,ci能夠是2.2或其餘html
大致思路:將smarty封裝成ci框架的一個類,而後從新配置一下smarty,這樣ci框架就能夠調用smarty模板引擎了框架
1. 將下載好的smarty包的lib文件上傳到ci中的libraries 文件中,將取名稱修改成smarty,在libraries文件新建cismarty.php文件,內容以下:函數
#require_once 記得要導入該smarty類文件測試
#$this->ci = & get_instance(); 獲取ci的超全局對象ui
#$this->ci->load->config('smarty'); 加載配置文件this
<?php
if(!defined('BASEPATH')) EXIT('No direct script asscess allowed');
require_once( APPPATH .'libraries/smarty/libs/Smarty.class.php' );
class Cismarty extends Smarty{
protected $ci;
public function __construct(){
$this->ci = & get_instance();
$this->ci->load->config('smarty');
parent::__construct();
$this->template_dir = $this->ci->config->item('template_dir');
$this->complie_dir = $this->ci->config->item('compile_dir');
$this->cache_dir = $this->ci->config->item('cache_dir');
$this->config_dir = $this->ci->config->item('config_dir');
$this->caching = $this->ci->config->item('caching');
$this->cache_lifetime = $this->ci->config->item('lefttime');
}
}
2. 在config下新建smarty.php配置文件spa
#第一個操做的代碼:$this->ci->load->config('smarty');將會調用到該配置文件code
#這裏的配置就是smarty裏的配置htm
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['theme'] = 'default';
$config['template_dir'] = APPPATH . 'views';
$config['compile_dir'] = APPPATH . 'views/templates_c';
$config['cache_dir'] = APPPATH . 'views/cache';
$config['config_dir'] = APPPATH . 'views/configs';
$config['caching'] = false;
$config['lefttime'] = 60;
$config['left_delimiter'] = '<{';
$config['right_delimiter'] = '}>';
3. 在CI裏重載smarty的 assign 和 display方法
#cismarty 必定要所有小寫,否則ci找不到。以前被坑在這裏了
#assign 該函數裏面要調用smarty類的assign方法才行
#display 該函數裏面要調用smarty類的display方法才行
<?php
if (!defined('BASEPATH')) exit('No direct access allowed.');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function assign($key,$val) {
$this->cismarty->assign($key,$val);
}
public function display($html) {
$this->cismarty->display($html);
}
}
4. 修改Config文件下的autoload.php 自動加載類文件
#$autoload['libraries'] = array('cismarty '); 實現自動加載smarty類
$autoload['libraries'] = array('cismarty ');
5. 下面測試
a. 新建控制器admin_welcome.php
#assign 調用MY_Controller類裏的assign方法,而後間接調用smarty的assign方法
#display 調用MY_Controller類裏的display方法,而後間接調用smarty的display方法
<?php
class Welcome extends MY_Controller {
public function index(){
$data = "datadatadata";
$this->assign("data", $data);
$this->display('test.tpl');
}
}
Views 下新建test.tpl
#$data 控制器傳來的值
<html>
<head>
</head>
<body>
aaaaaaaaaaaaaaaaaaaaa
{$data}
</body>
</html>