Smarty as a template engine in Code Igniter

Saturday, December 8, 2007

Smarty as a template engine in Code Igniter

In this article you will learn how to install and use Smarty as a template engine with Code Igniter Framework.

Update: 2009-09-28: updated download links.

Demo

A downloadable demo (including Smarty-2.6.18) is available from
http://slavi.biz/downloads/code-igniter/code-igniter-smarty.zip (~ 200 KB)

update (2007-12-13): an option added to pass params to mysmarty without calling assign Smarty method.
$this->mysmarty->view('module/func', $params);

http://slavi.biz/downloads/code-igniter/code-igniter-smarty-2.zip (~ 200 KB)

Code Igniter is a very good framework but there does have a *native* support for the Smarty template engine, it uses PHP code as template contents.

How to integrate

Things that you should keep in mind (when integrating this example into your projects)

1. You should add 'mysmarty' to autoloaded libraries in application/config/autoload.php

Example:
$autoload['libraries'] = array('database', 'mysmarty');

2. Copy Mysmarty.php to application/libraries

at the beginning of the file Mysmarty.php you can see the original smarty file structure.
I like this approach because it makes the updates easy, and/or downgrades (if any) in case of buggy new releases.

example
---
require "Smarty-2.6.18/libs/Smarty.class.php";
--


Example Usage of Smarty in Code Igniter:

application/controllers/welcome.php
-----------------------------------

mysmarty->assign('test', 'Hello World.');
$this->mysmarty->view('smarty');
}
}
-----------------------------------
Note:
$this->mysmarty should be available because we are auto loading this library.

view method is used to make an easier transition from code igniter's templates to Smarty ones.
view method also adds a '.tpl' extension if is not specified.


Example Smarty Template: application/views/smarty.tpl
-----------------------------------

{$test}

Def: {$def|default:'n/a'}
-----------------------------------

The file should be accessible via:
http://domain.com/path/to/code-igniter/index.php/welcome/smarty

where path/to/code-igniter is the path to code igniter index.php file.

Related Resouces:

Feel free to express your comments, suggestions, critics.

 Digg  Del.icio.us  Reddit  SlashDot

41 comments:

Vuk said...

Thanks.
The whole package is working like a charm.

Svetoslav Marinov said...

Hi. I am glad that you liked it.
As one of my friends (Didi) says "Happy Coding".

BlackBird said...

In the second archive, file Mysmarty.php, line 20 - error. Must be:
(!empty($config['smarty_template_dir']) ? $config['smarty_template_dir']

Svetoslav Marinov said...

Hi BlackBird,

This check is for compiled template files, not for templates.

Slavi

BlackBird said...

Yes, but there must be:
$this->compile_dir = (!empty($config['smarty_compile_dir']) ? $config['smarty_compile_dir'] ...

and in your file:

$this->compile_dir = (!empty($config['smarty_compile_dir']) ? $config['compile_dir'] ...

Try to set in the application/config/config.php: $config['smarty_compile_dir'] = 'some/path';
and you'll understand :-)

Svetoslav Marinov said...

Hi,

I see your point now, and it seems quite reasonable :)

thanks

Slavi

Svetoslav Marinov said...

The archive file (code-igniter-smarty-2.zip) is now updated.

Anonymous said...

you guys are good...

Svetoslav Marinov said...

Thanks :)

Anonymous said...

It's great. Thank you. I've tried the code but I got this message : Fatal error: ob_start() [ref.outcontrol]: Cannot use output buffering in output buffering display handlers in \....\system\libraries\Exceptions.php on line 160. Any idea how to solve this problem ?
Thank you.

Svetoslav Marinov said...

Hi,

sometimes the output can be started just by a single whitespace at the end of php files, so I would ask you to check the php files for trailing whitespaces after the closing php tag, or you could remove the closing php tag.

Slavi

Anonymous said...

The code went well in my Unix server without any modifications. After trying to trail the whitespace in the code for my windows server I still got the same error message.
I found the same problem in CI's forum in this link :
http://codeigniter.com/forums/viewthread/66951/#329611

Thanks for the advice.

katz said...

Hi,

I liked your code, and was wondering
if it is OK to redistribute your code with or without modificaiton?

Any advice would be very much appreciated. Thanks for your help in advance.

Svetoslav Marinov said...

Yes, sure.
No problem.
Thanks for asking.

DD said...

Smarty uses echo to display variables. This breaks output compression as indicated in the config file at $config['compress_output']. I don't have a solution yet.

Anonymous said...

Did you check the performance of solution Smarty and CodeIgniter together?

I did - it is very bad.

Such bad that if you have over 2000 UV site is just unusuable.

CI+Smarty is good just for not often visited home pages. Nothing else.

Svetoslav Marinov said...

DD:

Do you use display or fetch method of Smarty ?

Slavi

Svetoslav Marinov said...

Anonymous about 2000 Unique Visitors:

Where do you perform your caching ?

As far as I remember you can setup Smarty to create its cache files in deeper directory level, so this would speed up the loading of cached templates.

Thanks for benchmarking.

Slavi

Cris said...

Hi

benchmarking

With CI + smarty + smarty cache:
Loading Time Base Classes 0.0218
Controller Execution Time (Test / Index ) 0.0695
Total Execution Time 0.0914

With smarty + smarty cache:
0.008 sec

The difference is clear...

CI + smarty is good for a basic use of smarty not for a complex use (dynamic block, cache,...)

albayea said...

Thanks brotha

Chris H said...

Hi.
Thanks for your walkthrough. One thing I found that should improve on your code in the mysmarty.php file is to load the url helper through an instance of CI. Then $site_url should be accessible in smarty. Also I added the base_url code.
I hope this is clear for everyone [basically add the following lines to the Mysmarty function].

function Mysmarty()
{
$CI =& get_instance();
$CI->load->helper('url');

...

if (function_exists('base_url'))
{
// URL helper required
$this->assign("base_url", base_url()); // so we can get the path to CI easily
}

Svetoslav Marinov said...

Thanks for the suggestion.
Makes sense :)
Slavi

Girvan Information said...

Thanks for create this library, it is useful and I love'it!

Svetoslav Marinov said...

No Problem. :)

medianetix said...

Hi,
very smooth Smarty integration, like it very much.

For those who prefer the CI-style $this->load->view('template', $data):

I've changed the view-method in the Mysmarty class to:
--snip--
function view($resource_name, $vars = null, $cache_id = null) {
if (is_array($vars) && count($vars)>0) {
foreach($vars as $key=>$var){
$this->assign($key, $var);
}
}
if (strpos($resource_name, '.') === false) {
$resource_name .= '.html';
}
return parent::display($resource_name, $cache_id);
}
--snap--

So you can use $this->mysmarty->view('template', $data) and save some smarty->assigns :-)

Anonymous said...

nice work.

Anonymous said...

thank you, you rule, I use this in every project ... THANKS AGAIN

Svetoslav Marinov said...

No problem :)

accesine said...

great job.

thanks.


www.domolo.com

Anonymous said...

i'm doing what you told exactly but i'm template: [smarty.tpl] cannot be found.

zaak said...

beugh.. it's so complicated

Paulo said...

Hello Marinov, thanks your post. I have a problem with is_cached function in smarty. Not working.

private function _destaque(){

$this->mysmarty->caching = true;


if ($this->mysmarty->is_cached("coldirbot.tpl") ) {



$this->mysmarty->view('imoveis/coldirbot');



}

else {

$this->mysmarty->view('imoveis/coldirtop');



}

$this->mysmarty->caching = false;
}

help me.

thanks.

Svetoslav Marinov said...

Why would you disable and enable caching ?
Also did you check permissions of the cache folder ?

Take a look at: http://www.smarty.net/manual/en/caching.php

blue said...

I have a different approach on this. Because I like to use CodeIgniter without actually feeling I have smarty as template engine :)

If you are currious:
http://www.joy2share.com/code/log/smarty-CodeIgniter.html

Svetoslav Marinov said...

Thanks Blue.

Anonymous said...

your download links are broken : (

Svetoslav Marinov said...

Ooops!
I let the funcs.org domain to expire.
Sorry about that
I will fix the link.

Catalin Oprea said...

In order to make CI_Output class working, you must change last lines of view method with:

$CI = & get_instance();
return $CI->output->set_output(parent::fetch($resource_name));
}
}

Thanks anyway for the code :).

Svetoslav Marinov said...

Thanks Catalin Oprea.
In blogger it's hard to paste code....

Tio said...

Hello, I have problem with this error

Fatal error: ob_start() [ref.outcontrol]: Cannot use output buffering in output buffering display handlers in *system\libraries\Exceptions.php on line 162

I found, that probles is on line 49 in Mysmarty.php. This command "return parent::display($resource_name);" will echo output before ob_start(). You could turn of compression or replace this command by this:

$CI =& get_instance();
$CI->output->final_output = $this->fetch($resource_name);
return;

Svetoslav Marinov said...

thanks Tio for the fix.