一、下载Smarty模板和CI框架

1.https://codeigniter.org.cn/

2.Smarty官网https://www.smarty.net/

二、文件拷贝和扩展核心类库

1. 将下载下来的smarty-3.1.30(可以下载其他版本,原理一样)存放到application/libraries/目录下.

2. 在application/libraries目录下新建文件Cismarty.php,内容如下:

if(!defined('BASEPATH')) EXIT('No direct script asscess allowed');   

require_once( APPPATH . 'libraries/Smarty-3.1.30/libs/Smarty.class.php' );

class Cismarty extends Smarty {

protected $ci;

public function __construct(){

parent::__contruct; //原文这里未加此代码

$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'); //原文compile写成了complie

$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');

$this->left_delimiter = '<{';

$this->right_delimiter = '}>';

}

}


3. 在application/config的文件中新建smarty.php,内容如下:

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['theme'] = 'default';
$config['template_dir'] = APPPATH . 'views';
$config['compile_dir'] = FCPATH . 'templates_c';
$config['cache_dir'] = FCPATH . 'cache';
$config['config_dir'] = FCPATH . 'configs';
$config['caching'] = false;
$config['lefttime'] = 60;

4. 在入口文件创建'templates、cache、configs目录

5. 在application/config/下找到autoload.php文件

$autoload[‘libraries’] = array(‘cismarty’);

6. 在application/core目录下新建MY_Controller,内容如下

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

}

}


7. 新建控制器Test.php

class Test extends MY_Controller {

public function index()

{

$data['title'] = '标题';

$data['num'] = '123456789';

//$this->cismarty->assign('data',$data); // 亦可

$this->assign('data',$data);

$this->assign('tmp','hello');

//$this->cismarty->display('test.html'); // 亦可

$this->display('test.html');

}

}


8. 新建视图test

<!DOCTYPE html>   

<html>

<head>

<meta charset="utf-8">

<title>{ $test.title}</title>

<style type="text/css">

</style>

</head>

<body>

{$test.num|md5}

<br>

{$tmp}

</body>

</html>


9. 配置完成.