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:


41 comments:
Thanks.
The whole package is working like a charm.
Hi. I am glad that you liked it.
As one of my friends (Didi) says "Happy Coding".
In the second archive, file Mysmarty.php, line 20 - error. Must be:
(!empty($config['smarty_template_dir']) ? $config['smarty_template_dir']
Hi BlackBird,
This check is for compiled template files, not for templates.
Slavi
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 :-)
Hi,
I see your point now, and it seems quite reasonable :)
thanks
Slavi
The archive file (code-igniter-smarty-2.zip) is now updated.
you guys are good...
Thanks :)
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.
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
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.
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.
Yes, sure.
No problem.
Thanks for asking.
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.
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.
DD:
Do you use display or fetch method of Smarty ?
Slavi
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
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,...)
Thanks brotha
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
}
Thanks for the suggestion.
Makes sense :)
Slavi
Thanks for create this library, it is useful and I love'it!
No Problem. :)
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 :-)
nice work.
thank you, you rule, I use this in every project ... THANKS AGAIN
No problem :)
great job.
thanks.
www.domolo.com
i'm doing what you told exactly but i'm template: [smarty.tpl] cannot be found.
beugh.. it's so complicated
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.
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
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
Thanks Blue.
your download links are broken : (
Ooops!
I let the funcs.org domain to expire.
Sorry about that
I will fix the link.
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 :).
Thanks Catalin Oprea.
In blogger it's hard to paste code....
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;
thanks Tio for the fix.
Post a Comment