配置
下载ci框架和smarty, 创建项目目录
# /var/www 为web根目录
$ cd ~/download
$ wget https://codeload.github.com/bcit-ci/CodeIgniter/zip/3.0.6
$ wget https://codeload.github.com/smarty-php/smarty/zip/v3.1.29
$ unzip CodeIgniter-3.0.6.zip
$ unzip smarty-3.1.29.zip
$ mv CodeIgniter-3.0.6 /var/www/ci_smarty
$ mv smarty-3.1.29/libs /var/www/ci_smarty/application/libraries/smarty3.1.29
在 /var/www/ci_smarty/application/libraries 目录下创建 CI_Smarty.php 文件
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'libraries/smarty3.1.29/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');
}
}
在 /var/www/ci_smarty/application/config 目录下创建 smarty.php 文件
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['cache_lifetime'] = 60;
$config['caching'] = true;
$config['template_dir'] = APPPATH .'views';
$config['compile_dir'] = APPPATH .'views_c';
$config['cache_dir'] = APPPATH . 'cache/views';
$config['config_dir'] = APPPATH . 'views/config';
$config['use_sub_dirs'] = false; //子目录变量(是否在缓存文件夹中生成子目录)
$config['left_delimiter'] = '{';
$config['right_delimiter'] = '}';
在 /var/www/ci_smarty/application/core 目录下创建 MY_Controller.php 文件
<?php
class MY_controller extends CI_Controller
{
public function __construct()
{
date_default_timezone_set("PRC");
parent::__construct();
}
public function assign($varname,$var)
{
$this->ci_smarty->assign($varname,$var);
}
public function display($template)
{
$this->ci_smarty->display($template);
}
}
使用方法
加载smarty类
有两种方法, 如果随时会用到, 推荐使用自动加载办法:
- 在 ci框架的配置目录 config 下的 autoload.php 中自动加载类增加 smarty 类
$autoload['libraries'] = array('ci_smarty');
- 直接执行 ci 的加载类方法:
$this->load->library("Ci_smarty");
使用smarty
- 在ci默认控制器 Welcome.php 中, 修改 index
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends MY_Controller {
public function index()
{
$test='ci 3.0.6 结合 smarty 3.1.2 配置成功';
$this->assign('data',$test);
$this->display('test.html');
}
}
- 在 views 目录, 创建 test.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>smarty结合ci使用测试</title>
</head>
<body>
{$data}
</body>
</html>
- 浏览器访问: localhost/ci_smarty, 输出:
ci 3.0.6 结合 smarty 3.1.2 配置成功