Integrating CodeIgniter 3 and Smarty 3 is easy

Using Smarty 3 with CodeIgniter 3 is easy.

I decided to upgrade a CI2/Smarty2 project to the latest versions. Refactoring the CI2 code to CI3 was easy enough using the guidelines (Upgrading from 2.2.x to 3.0.x) and the Smarty 3 upgrade was as easy as replacing the old libraries with the new version. Getting them to work together was more interesting. Some of the CI naming conventions have changed with CI3, which is highly sensitive to the case of object names. After a lot of debugging, this worked:

Copy the Smarty 3 libraries into CI application/third_party folder.

Add a custom library definition in application/libraries/My_Smarty.php

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

require_once( APPPATH.'third_party/smarty/libs/Smarty.class.php' );

class My_Smarty extends Smarty
{
    public function __construct()
    {
        parent::__construct();

        $this->setTemplateDir( APPPATH . "views/templates");
        $this->setCompileDir( APPPATH . "views/compiled");
        $this->setCacheDir( APPPATH . 'third_party/smarty/cache');
        $this->assign( 'APPPATH', APPPATH );
        $this->assign( 'BASEPATH', BASEPATH );

        // Assign CodeIgniter object by reference to CI
        if( method_exists( $this, 'assignByRef') )
        {
            $ci =& get_instance();
            $this->assignByRef("ci", $ci);
        }

        //log_message('debug', "Smarty Class Initialized");
    }

    function view($template, $data = array(), $return = FALSE)
    {
        foreach($data as $key => $val)
        {
            $this->assign($key, $val);
        }

        if($return == FALSE)
        {
            $CI =& get_instance();
            if(method_exists( $CI->output, 'set_output' ))
            {
                $CI->output->set_output( $this->fetch($template . '.html') );
            }
            else
            {
                $CI->output->final_output = $this->fetch($template . 'html');
            }
            return;
        }
        else
        {
            return $this->fetch($template);
        }
    }
}

 

Load the custom library in application/config/autoload.php

$autoload['libraries'] = array('database',  'my_smarty');

Use the custom Smarty class in your controller with:

$this->my_smarty->assign("mega_title","Staff");
$this->my_smarty->assign("base_url",base_url());
$this->my_smarty->assign("message","");
$this->my_smarty->assign("result",$query->result());
$this->my_smarty->view('staff_view_all');

 

1,847 views

Need help? Let me take care of your IT issues.

Share this page

Scroll to Top