CodeIgniter: Smarty as a full-fledged template engine

CodeIgniter

I’m a newly converted fan of the CodeIgniter (CI) framework for PHP. I was introduced to it a few weeks back, and there’s been no looking back. PHP has suffered much critique of late here, here and here, but if there’s a star example of beautiful PHP code, here’s it. It helps developers write code better, period.

I really like the many libraries and helpers available, they make the many tiresome things (forms, pagination, input validation) that are rehashed every time a new web application is written a joy, since this is all done for you already. Not that I would recommend someone new to web development to CI, since I’m an advocate of the fact that you must go through some pain to appreciate the beauty in things. But then I digress.

I’m not so keen about the template parsing part though. I had almost expected something like Smarty, but guess I was spoilt. I felt that mixing PHP/HTML syntax was simply… ugly. Tsk, tsk. The user guide indicates that it was an intentional decision to not include a full-blown templating solution, and I think CI suffers for that fact.

So… why not combine CI and Smarty? Note that this is not a CI or Smarty tutorial, if you need help on those things, read the manual! :) According to CI convention, I’ve put the Smarty source code into the libraries folder. Since there are quite a number files, I put it in a subfolder “smarty”, so the path to Smarty is:

system/application/libraries/smarty/Smarty.class.php

Now, we need to extend the Smarty (we’ll call it smarty_library), the code which we stored as:

system/application/libraries/smarty_library.php

There are plenty of Smarty configurations to play around with, but we’ll stick to just two (template_dir and compile_dir). Using absolute paths help prevent those pesky “template not found” errors.

Smarty();

		// absolute path prevents 'template not found' errors
		$this->template_dir = '/path/to/CodeIgniter/system/application/views/'; // use CI's views folder
		$this->compile_dir = '/path/to/CodeIgniter/system/cache/'; //use CI's cache folder -- chmod 777 cache required

		// URL helper required
		$this->assign('site_url', site_url()); // so we can get the full path to CI easily
	}
} // END class smarty_library
?>

Now that this is done, you can put the library load call in your CI application as:

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

Access your Smarty object at:

$this->smarty->assign('foo', $foo);

Please drop comments! I’d love to hear from other like-minded developers! :)

Advertisements

30 thoughts on “CodeIgniter: Smarty as a full-fledged template engine

  1. Perhaps you might want to modify class CI_Smarty slightly to use the config settings (if present)?

    $config =& get_config();

    $this->template_dir = ($config[‘smarty_template_dir’] != ”) ? $config[‘smarty_template_dir’] : BASEPATH.’application/views/smarty/’;

    $this->compile_dir = ($config[‘smarty_compile_dir’] != ”) ? $config[‘compile_dir’] : BASEPATH.’cache/’; //use CI’s cache folder

  2. Yes… I was not aware of this get_config() method, under:

    system/codeigniter/Common.php

    Its a better idea to take stuff from CI, since logically speaking, we are putting Smarty into CI.

    Thanks for the tip!

    :)

  3. Thanks for this great writeup. I’ve had difficulty finding a good resource on how to incorporate Smarty into CodeIngiter.

    Like you, I’ve recently been introduced to CodeIgniter, and, despite being a Zend Framework nut, I’ve not looked back either. But I guess, like you, I was spoiled by Smarty.

    I noticed right from the start really, that CodeIgniter was lacking quite a bit in the templating department. All of the clients I work with are very familiar with Smarty and designers, myself included, just find it much easier to work with. This way I can keep those pesky designers out of my code ;)

  4. I’ve never used Zend Framework: never looked back since CodeIgniter!

    I guess Smarty appeals alot to the designer folks simply because it looks pretty similar to HTML, as opposed to sprinkling PHP syntax inline!

  5. Wayne, I’m new to Code Igniter so forgive the question: where is the best place to put the $this->load->library(’ci_smarty’); line?

    Thanks for a really easy to understand article!

  6. Hello Jim,
    You are most welcome. You can put it in two locations:

    1. autoload.php
    2. in your controller’s constructor (e.g. foo.php)

    Putting in #1 will make $this->ci_smarty available in all your controllers.
    Otherwise if #2, it will only be available in Foo.

    /**
    * @file system/application/config/autoload.php
    */
    $autoload[‘libraries’] = array(“ci_smarty”);

    /**
    * @file system/application/controllers/foo.php
    */
    function Foo()
    {
    parent::Controller();
    $this->load->library(“ci_smarty”);
    }

  7. Thanks Wayne. After years of using it, I need Smarty like food and water!

    Do you have any other favorite CI tweaks? (I’m new to CI)

    Thanks to Mike Kruger for his insightful suggestion, too!

    – Jason
    Memphis, TN

  8. Hi there, I’ve just found this article and it seems perfect for what I need… however! I’m have a real pain trying to get it working… I have followed the instructions perfectly, but I keep getting the following error:

    “Unable to load the requested class: smarty”

    I’m trying to load them via the application autoloader.

    I have echoed out the filepath from loader.php and that states:

    smarty path: D:\www4/system/application/libraries/Smarty.php
    smarty path: D:\www4/system/libraries/Smarty.php
    smarty path: D:\www4/system/application/libraries/smarty.php
    smarty path: D:\www4/system/libraries/smarty.php

    Am I missing something here?

  9. Toby,

    You need to modify this:
    $this->load->library(“smarty_library”, “smarty”);

    The second argument doesn’t work in CI. I was wondering why nobody else caught that…

    Anyway, You should just load the library as:
    $this->load->library(“smarty_library”);

    And then refer to it as $this->smarty_library, wherever you use it.

    Unfortunately you can’t just call it smarty because that is already the name of the actual Smarty class.

    Has anybody found a nice way to get to keep it named “smarty” without “_library”?

  10. This is a great article and totally assisted me in moving from Zend Framework to CI and like the rest here I was spoilt by Smarty as it is the best Templating solution imho.

    Here is my implementation, I call the wrapper Tp for easy reading/writing and include the ability to turn on/off caching behavior for development.

    <<<<<<<< /application/libraries/Tp.php <<<<<<<<<Smarty();
    $config = & get_config();

    $this->template_dir = ($config[‘template_dir’] != ”) ? $config[‘template_dir’] : BASEPATH.’application/views’;

    $this->compile_dir = ($config[‘compile_dir’] != ”) ? $config[‘compile_dir’] : BASEPATH.’application/libraries/Smarty/templates_c’;

    $this->config_dir = ($config[‘config_dir’] != ”) ? $config[‘config_dir’] : BASEPATH.’application/libraries/Smarty/configs’;

    $this->cache_dir = ($config[‘cache_dir’] != ”) ? $config[‘cache_dir’] : BASEPATH.’application/libraries/Smarty/cache’;

    $this->caching = $cache;
    $this->cache_lifetime = $cache_lifetime;
    }
    }//:>~
    ?>

  11. Thank you for all the advices that you wrote here. Here is what I did:

    1) I added the following lines to application/config/config.php

    $config[‘smarty_template_dir’] = ”;
    $config[‘smarty_compile_dir’] = ”;

    2) I created a folder called “smarty” in application/libraries and I’ve put the smarty library there.

    3) I’ve created a file “Smarty.php” in application/libraries that contains the following code:

    Smarty();

    // absolute path prevents “template not found” errors
    $config =& get_config();
    $this->template_dir = ($config[‘smarty_template_dir’] != ” ? $config[‘smarty_template_dir’] : BASEPATH.’application/views/smarty/’);
    $this->compile_dir = ($config[‘smarty_compile_dir’] != ” ? $config[‘compile_dir’] : BASEPATH.’cache/’); //use CI’s cache folder

    // URL helper required
    //$this->assign(“site_url”, site_url()); // so we can get the full path to CI easily
    }
    } // END class smarty_library
    ?>

    4) Since I intend to use smarty in my application I’ve modified the application/config/Autoload.php file to contain:

    $autoload[‘libraries’] = array(‘smarty’);

  12. Great stuff dude! :)

    took me a while to get it all going, but works perfectly now! :)
    too bad we must reference it with “smarty_library” though, but if I get some better solution -> I’ll scream right back here! ;)

    Thanks,
    dootzky!

  13. Hi guys,
    I have a little problem with the integration.
    everything works fine, but in the templates files (*.tpl)
    I can’t use stuff like that:

    of
    it just doesn’t process the php code

    any idea?

  14. Great stuff – nice to read.

    Has anyone had any luck assigning (by reference or otherwise) a codeigniter CI instance to Smarty for use within the templates? I have this working with no problems in Smarty v2 but not in Smarty v3 (Smarty3).

    1. Andrew, this is a really old post.

      I’ve stopped using CodeIgniter/Smarty, but I did try it out the new versions (2.0.2, 3.0.8) and it seems to work fine, you need to use the get_instance() method documented in http://codeigniter.com/user_guide/general/creating_libraries.html; e.g.

      I tried out CodeIgniter 2.0.2/Smarty 3.0.8, and found that it is possible to assign the CodeIgniter object to Smarty; e.g.

      https://github.com/kzhiwei/codeigniter-smarty/blob/master/application/libraries/Smartylib.php

      Hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s