• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Working With CodeIgniter Smarty Together

Working With CodeIgniter Smarty Together

June 7, 2011 by Rana Ahsan 3 Comments

smarty

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? 😀

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: codeigniter, php, smarty, web application

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. muhammad says

    February 7, 2012 at 3:37 am

    very nice … going to implement it now … will see if any issues…thank you,

    Reply
  2. Divya says

    March 11, 2015 at 11:13 pm

    How can i include header.php/tpl and footer pages dynamically without creating assoc array? please suggest

    Reply

Trackbacks

  1. Guidelines And Best Practices For Codeigniter Development | codesamplez.com says:
    November 20, 2012 at 2:47 am

    […] some basic idea, but looking for integrating it on codeigniter, you can read another article on how to integrate smarty in codeigniter.Using third party data access layer library:Codeigniter has a very good data manipulation library […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023