Codeigniter框架整合Smarty引擎DEMO

来源:互联网 发布:java编程思想 在线 编辑:程序博客网 时间:2024/05/16 02:00

        Smarty的模板机制很强大,一般情况下CI框架无需整合其他模板标签,因为PHP本身就是一种标签,简单易用。Codeigniter整合Smarty教程(我用的都是最新版本)如下:

        第一步:下载Codeigniter最新版本:CodeIgniter框架源码
        第二步:下载Smarty最新版本:Smarty引擎源码
        第三步:具体配置

我已将本人整合好的代码上传,有兴趣的可以下载阅读。Codeigniter框架整合Smarty引擎DEMO

1、准备

        将smarty拷贝到application/libraries下,然后再根目录下下新建templates,templates_c,config,cache目录,结构如下:


2、修改入口文件

        在入口文件index.php中新增:

    define('ROOT', dirname(__FILE__));

3、新建CI_Smarty.php

        在libraries文件下新建CI_Smarty.php,写如下代码:

    <?php        /**     * =======================================     * Created by PK Technology.     * Author: ZhiHua_W     * Date: 2016/10/31 0031     * Time: 上午 9:16     * Project: CI整合     * Power:  CI框架整合smarty     * =======================================     */        defined('BASEPATH') OR exit('No direct script access allowed');        require(APPPATH . 'libraries/smarty/Smarty.class.php');        class CI_Smarty extends Smarty    {        public function __construct($template_dir = '', $compile_dir = '', $config_dir = '', $cache_dir = '')        {            parent::__construct();            if (is_array($template_dir)) {                foreach ($template_dir as $key => $value) {                    $this->$key = $value;                }            } else {                //ROOT是Codeigniter在入口文件index.php定义的本web应用的根目录                $this->template_dir = $template_dir ? $template_dir : ROOT . '/templates';                $this->compile_dir = $compile_dir ? $compile_dir : ROOT . '/templates_c';                $this->config_dir = $config_dir ? $config_dir : ROOT . '/config';                $this->cache_dir = $cache_dir ? $cache_dir : ROOT . '/cache';            }        }    }

4、在controller中使用

        在控制器Welcome.php中写入使用方法,代码如下:

    <?php        defined('BASEPATH') OR exit('No direct script access allowed');        class Welcome extends CI_Controller    {            /**         * Welcome constructor.         * 写入构造函数,引入CI_Smarty类文件         */        public function __construct()        {            parent::__construct();            $this->load->library('CI_Smarty');        }            /**         * smarty测试函数         */        public function test()        {            $this->ci_smarty->assign('test', 'smarty');            $this->ci_smarty->display('test.tpl');        }    }

5、创建模版试图

        在templates文件夹下创建test.tpl文件,写入如下代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Codeigniter整合Smarty测试</title></head><body>这是 {$test} 测试</body></html>

6、访问

至此,我们整合完毕,访问:http://localhost/Codeigniter_Smarty/index.php/Welcome/test即可看到测试结果。

0 0
原创粉丝点击