Codeigniter 中集成smarty
Ci是個不錯的框架,Smarty是一個不錯的模板引擎,网上看了很多,也不知道是版本问题还是什么, 总是配置不成功,多次试验终于OK。對於结合Smarty的配置步骤如下:
1. 第一步配置ci和下载smarty的模板。
Codeigniter版本为2.1.2,Smarty版本为3.1.11。
2. 第二部把下载到的smarty版本解压然后把里面的libs文件改名为smarty然后把这个文件拷到ci的\application\libraries目录下面
目錄結構是:application\libraries\Smarty\Smarty.class.php
3. 在ci\application\libraries这个目录下面建立一个文件,文件名可以自定义,例如见一个Cismarty.php的文档。
4. 用编译器打开Cismarty.php然后写入以下代码:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/Smarty/Smarty.class.php' );
class Cismarty extends Smarty {
var $CI;
public function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->template_dir = APPPATH.'views';
$this->compile_dir = APPPATH.'templates_c/';
$this->cache_dir = APPPATH."cache/";
$this->left_delimiter = '{';
$this->right_delimiter = '}';
}
}
5. 在建立一个ci\application\templates_c文件夹
6. 打开ci\application\config\autoload.php文件
把$autoload[‘libraries’] = array();改成$autoload[‘libraries’] = array(‘database’,’cismarty’);
或者在使用的時候load也可:$this->load->library(‘cismarty’);
建立控制器text.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Text extends CI_Controller {
/**
* Text construtor
*/
public function __construct()
{
parent::__construct();
$this->load->library('cismarty');
$this -> load->helper('url');
//定義CSS、JS路徑
$this -> cismarty -> assign('base_url',base_url());
}
/**
* Index Page for this controller.
*/
public function index()
{
$this -> cismarty -> assign('title','測試頁面');
$this -> cismarty -> display("text.html");
}
}
建立模板文件text.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試頁面</title>
</head>
<body>
{$base_url}
<p>模板內容</p>
{$title}
</body>
</html>
打開瀏覽器, 通過瀏覽 index.php/text 即可查看效果