Working With CodeIgniter Smarty Together


 Working With CodeIgniter Smarty Together  
 

Before, I have written tutorials about smarty basics as well as codeigniter tutorial for beginners. As the ci framework doesn’t include any template engine, many developers love to use smarty with codeigniter based application as the view engine.Tn this tutorial, i will try to guide you through how to integrate smarty template engine library in codeigniter framework and how can we use it in most efficient way easily. I am assuming, you have some basic knowledge with both smarty and codeigniter, if not, i recommend to read about their basics first. You are gonna love the power of codeigniter smarty pair!


Read The Complete CodeIgniter Tutorials Series By CodeSamplez.com

Download and installing:

First we need to have the latest codeingiter and smarty library versions. first, unzip and place the codeginiter files to your local ‘htdocs’ directory. then unzip the smarty library and place the ‘smarty’ directory inside the codeigniter’s ‘application/third_party’ directory. Now, we can reuse the ‘mysmarty’ class that we used on smarty basic tutorial. place that to ‘application/libraries’ directory. Now, as we will need this library every time a page loaded, its good to load our library with auto load option. so, add ‘mysmarty’ to the autoload libraries array in ‘application/config/autoload.php’ file.

Usage Example:

Simply, now we just have to assign values to smarty variables, call display method with proper template file name. Following is a sample code snippet of a codeigniter controller class:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* @property CI_Loader $load
* @property CI_Form_validation $form_validation
* @property CI_Input $input
* @property CI_Email $email
* @property Mysmarty $mysmarty
*/

class Home extends MY_Controller
{
    /**
     * constructor
     */
    public function __construct()
    {
        parent::__construct();        
    }
    
    /**
     * Default function that will be executed unless another method specified
     */
    public function index()
    {  
        // basic assignment for passing data to template file
        $smarty->assign('title', 'Test Title');
        $smarty->assign('description', 'Test Description');
       
        // show the template
        $smarty->display('index.tpl');         
    }

And here is the sample template file that is located in ‘application/views’ directory.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Smarty Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />         
  </head>
  <body>
      <div class="container" id="container">
      	<h2>{$title}</h2>
        <p>{$description}</p>
      </div>          
  </body>
</html>

Codeigniter Smarty View Transformation/Mirgration:

It’s general case that, you might have already started with built-in codeigniter views and now getting interested to use smarty as the view. Sure, you can do this also, no doubt. Simply follow the following steps to meet such goal. Also, even you are starting new application and has no issue of such migration, you should follow the following procedure as your application’s best practice that will help you to switch between smarty view and codeigniter view very easily with minimal effort.

using a common ‘MY_Controller’ : You should use a common MY_Controller for your codeigniter application, that will inherit core ‘CI_Controller’ and initialize all common functionality for all controller. Also, every controller should inherit this ‘MY_Controller’ instead of core controller. Following is a sample MY_Controller class(it should be on ‘application/core’ directory):

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

/**
 * CodeIgniter MY_Controller Class
 *
 * initializes common controller settings, this is to be derived by all controllers of this application
 *
 * @name	MY_Controller 
 * @category	Core Libraries
 * @author	Md. Ali Ahsan Rana
 * @link	http://codesamplez.com/
 */

/**
 * @property Mysmarty $mysmarty
 */
class MY_Controller extends CI_Controller
{    
     /**
     * constructor
     */
    function __construct()
    {
        parent::__construct();                       
    }
   
    /**
     * final view codes for showing template
     */
    function view($template,$data=NULL)
    {
        //assigns all data as smarty variables. Reduces smarty assignment in controllers
        if($data != NULL)
        {
            foreach($data as $key => $value)
            {
                $this->mysmarty->assign($key, $value);
            }
        }       
       
        $this->mysmarty->display($template.".tpl");
    }    
}

Convert controller methods: Now, you will have to convert the codes of controllers for applying the smarty templates instead of codeigniter views. Lets assume you have a controller method as like follows:

     public function about()
    {
        $data["message"] = "About Smarty And Codeigniter";
        return $this->load->view("about",$data);
    }

Now, assuming that, the corresponding controller does inherit ‘My_Controller’ class, lets just change the ‘$this->load->view(“about”,$data)’ to ‘$this->view(“about”,$data)’, that is just remove the ‘load->’ part , will do the work we needed. This will trigger the ‘view’ method of ‘My_Controller’ class that the controller inherited and will execute necessary smarty codes to do the rest. Its pretty easy, isn’t it? :D

Now, just remember that, if you have used the current format from beginning, you can switch to any template mode anytime just by modifying the MY_Controller’s view method.

Hope this small tutorial will help you get started with using smarty with codeigniter framework. If you are having some issues or have some inquiry, please let me know by commenting below, I will try to help as much as possible. Happy coding :)

Comments

Trackbacks

Leave a Reply