CI框架与Smarty模板引擎整合步骤

smarty-3.1.30模板引擎下载:https://pan.baidu.com/s/1o7UTPNG

smarty 官网地址:https://www.smarty.net/ 

CodeIgniter-3.1.0框架下载:https://pan.baidu.com/s/1jHXJQ8A

首先,把下载到的smarty模板引擎解压,然后把里面的libs文件夹改名为smarty,然后把这个文件夹整体复制到ci\application\libraries目录下面;

然后,在ci\application\libraries目录下面建立一个文件,文件名可以自定义,例如创建一个tp.php文件,打开文件,在文件中写入以下代码:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once('smarty/smarty.class.php'); class Tp extends Smarty{     function tp(){         parent::__construct();         $this->template_dir = APPPATH.'views';         $this->compile_dir = APPPATH.'templates_c/';         $this->left_delimiter = '<{';         $this->right_delimiter = '}>';     } }

之后,建立一个ci\application\templates_c文件夹,然后,打开ci\application\config\autoload.php文件,把$autoload[‘libraries’] = array();改成$autoload[‘libraries’] = array(‘database’, ‘tp’);

OK,现在CI框架与Smarty模板引擎已经整合成功,下面我们测试一下效果!

  1. 在ci\application\controllers下建立一个文件名为test.php的文件,文件内容如下:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class test extends CI_Controller {     function __construct()     {         parent::__construct();         $this->load->helper('url');         $this->tp->assign('base_url', base_url('resource'));     }     function index()     {         $this->tp->assign("title","恭喜你smarty安装成功!");         $this->tp->assign("body","欢迎使用smarty模板引擎");         $arr = array(1=>'zhang',2=>'xing',3=>'wang');         $this->tp->assign("myarray",$arr);         $this->tp->display('test.html');     } }

2.建立html文件,在ci\application\views目录下,建立文件名为test.html的文件,文件内容为:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src='<{$base_url}>/js/jquery-2.1.1.min.js' type='text/javascript' ></script> <link href="<{$base_url}>/css/bootstrap.css" rel="stylesheet" type="text/css" /> <title>smarty安装测试</title> </head>     <body>     <h1><{$title}></h1>     <p><{$body}></p>         <ul>             <{foreach from=$myarray item=v}>             <li><{$v}></li>             <{/foreach}>         </ul>     </body> </html>

3.配置路由跳转,打开ci\application\config\routes.php,在文件最下方,添加语句$route[‘test’] = “test”;

最后,在任意浏览器输入地址http://localhost/ci/test,即可看到效果!(注意ci代表的是工程文件的根目录)。

原文链接:http://www.phpthinking.com/archives/807

转自:http://blog.csdn.net/ityang521/article/details/52875556