CodeIgniter中使用Smarty模板引擎

在CodeIgniter框架中,parser解析方式不是很完善,所以想换用smarty模版引擎。

方法如下:


1、下载smarty源码包,解压后将其中的lib文件夹复制到CI框架中的application/library/下面;


2、同时在该目录下建立一个Cismarty.php文件,文件内容如下:


<?php 

 if ( ! defined('BASEPATH')) exit('No direct script access allowed');

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

/**

 * Smarty Class

 *

 * Lets you use smarty engine in CodeIgniter.

 *

 * @package        Application

 * @subpackage    Libraries

 * @category    Customize Class

 * @author        sharexie

 */

class Cismarty extends Smarty {


    var $CI;


    /**

     * Smarty constructor

     *

     * The constructor runs the session routines automatically

     * whenever the class is instantiated.

     */

    public function __construct()

    {

        parent::__construct();


        $this->CI =& get_instance();

        $this->template_dir = APPPATH . 'views/';

        $this->compile_dir = 'cache/templates_c/';

        //$this->config_dir = $CI->config->item('configs_dir');

        //$this->cache_dir = $CI->config->item('cache');

        //$this->caching = true;

        //$this->cache_lifetime = ;

        //$this->debugging = true;

        $this->left_delimiter = '{#';

        $this->right_delimiter = '#}';

    }


    // --------------------------------------------------------------------


    /**

     * An encapsulation of display method in smarty class

     *

     * @access    public

     * @param    string

     * @param   mixed

     * @return    void

     */

    public function view($template_file, $assigns = array())

    {

        if (strpos($template_file, '.') === false)

        {

            $template_file .= '.html';

        }


        if ( ! is_file($this->template_dir . '/' . $template_file)) {

            show_error("Smarty error: {$template_file} cannot be found.");

        }


        if (is_array($assigns) && !empty($assigns))

        {

            foreach ($assigns as $key => $value)

                $this->assign($key, $value);

        }


        $this->display($template_file);

    }

}

/* End of file Smarty.php */

/* Location: ./application/libraries/Smarty.php */


//================================================================

配置完毕

//================================================================

使用方法:

在控制器中如:


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Test extends CI_Controller {


    /**

     * Test construtor

     */

    public function __construct()

    {

        parent::__construct();

                $this->load->library('smarty');

    }

        /**

     * Index Page for this controller.

     */

        public function index()

    {        

        $this->cismarty->view('test',array('title'=>'测试'));

    }

}


在视图中如:


<html>

<head>

    <title>{#$title#}</title>

</head>

<body>


<p>work well</p>


</body>

</html>


原文链接:https://www.cnblogs.com/fredshare/archive/2012/04/13/2445840.html