Codeigniter is an awesome framework, it’s idea of a parser library that ships with it is not. I have written a simple library that extends Codeigniter’s native view loading to allow you to use Smarty 3 in your Codeigniter projects to render your views.
Requirements:
- Codeigniter 2.0 as this library uses the core and third_party folders, although with some changes it will work with 1.7.2 / 1.7.3 versions of Codeigniter.
Features:
- Extends native Codeigniter view loading so you can still use $this->load->view() to load your templates. This also means that if your Codeigniter application is using $this->load->view() you won’t need to change any of your code to use this library.
- Allows you to use Smarty specific features including template inheritance inside of your views.
- Uses your views directory for loading templates but the location of views can be changed if you don’t use the standard CI views folder.
- Comes bundled with the latest version of Smarty already.
Install:
Copy all of the files from the download zip off the repo into your application directory. Then you should be able to just load Smarty views using the native $this->load->view() notation.
Download:
Download this library fresh off the press on it’s own Github repository, here.
Update Log:
- Thursday, 17th February 2011 – Added in configuration file. Added in default needed cache directories. A change to note from a few days ago is the CI superobject is assigned by reference to the views using the variable name “this” which means you should be able to go $this->load->view() inside of your views or any other native CI stuff (all untested though).
- Friday, 3rd December 2010 – Added in check for a file extension, if no file extension is found views will search for a file with a .php extension much like standard CI view loading works.
Feel free to post improvements and recommendations below if you’ve made some improvements or found that it doesn’t function correctly.
Note: Keep in mind that in this package I am using a custom MY_Loader file in the core directory to extend the native view functionality of Codeigniter, so if you are using Modular CI, Modular Extensions or already have a custom MY_Loader file in your core directory you might want to copy and paste the code into the pre-existing file yourself or you may lose existing functionality.
Hi Dwayne,
Great thanks for your plugin.
However, I found something might be a bug:
in application/libraries/Smartyp.php
$this->compile_dir = SYSDIR.”cache/smarty/compiled”; // Where templates are compiled
$this->cache_dir = SYSDIR.”cache/smarty/cached”; // Where templates are cached
the SYSDIR is Name of the “system folder” without ending ‘/’
Is it should be $this->compile_dir = SYSDIR.”/cache/smarty/compiled”; ?
Hi Rick,
You are absolutely correct. I might just change it to be BASEPATH.”cache/compiled” instead which should work because BASEPATH is the path to the system folder and is used in the index.php bootstrap file to include the main Codeigniter core files. Thank you for pointing out the error, I am going to fix it now and re-upload the file.
hi! might actually sound dumb because i’m quite like a beginner to CodeIgniter (been working with Smarty before tho, but it was already set up), but – how do I make it work and use it?
I’ve downloaded your package, put all the files in the needed location, and inluded “smartyp” library in autoload libraries. don’t get any errors yet, but any changes neither. if that’s correct – what’s the next step and how does it improve the whole thing?
thank you in advance, been trying to combine them two for almost a week already, and haven’t succeeded, really, i need some help with this, already driving me crazy..
cheers!
Hi Edzjins,
In the zip file if you look in the controllers folder you will notice a test controller would have been copied over called “smartytest” without the quotes of course. Try visiting the url you installed Codeigniter and the Smarty library in and visiting the test controller. You should see the test page.
So:
(If you haven’t removed the index.php file)
http://localhost/wherecodeigniteris/index.php/smartytest
http://localhost/wherecodeigniteris/index.php/smartytest/inheritance
(If you have removed the index.php file)
http://localhost/wherecodeigniteris/smartytest
http://localhost/wherecodeigniteris/smartytest/inheritance
This library basically overwrites the $this->load->view call you will be making to load views in your controllers and allows Smarty to parse your view files instead letting you have greater and cleaner control over your views.
Hi Dwayne,
Thanks for the quick answer, really appreciate that.
I open the both links, but all I see is an empty page. As I understand, there should be some header text and some body text appearing, but it itsn’t. When I view the source of the page, it’s just nothing. Not even the tag etc. What could be the problem?
Thanks again!
Hi Rick,
Yep, checked the log, no errors. And, the folder is 777. Really strange, because there seem to be no errors, the folders are just fine, but it’s just… not working!
Edzjins,
Have you still got the welcome controller that came with Codeigniter? Open up the welcome view file in your views folder and edit the file to use Smarty variables and remove the PHP code and see if that works.
No, I’m already having my created controller, let’s call it Blog. Works fine with the controller calling “head, $data”, “body, $data” and “foot” views from each function. “head” and “body” views use the CI-way of displaying the passed variables just fine, when I try to replace them with smarty-style variables in the views, they just output like a text, for example, “{$title}”, and that’s all.. no errors show etc. nothing hangs up either. just don’t know what to do now, when got it all set up etc.
when I copy the MY_Loader.php file to /application/libraries/, everything goes white, i guess that means it’s broken. I decided to check CI User Guide and see what it says about extending core classes, and it has quite a different way of doing it than this solution.. i tried to change this one to the way it tells in the user guide, but no success, the same result.
am i the only one getting a result like this? as i see, if you’re even on the smarty home page, this should be something cool, and people have good feedback about this. i guess i’m just damned not to be able to succeed to finish this project till deadline..
You are using Codeigniter 2.0 right? Not 1.7.2? You should be able to just copy the folders from within the zip file into your application directory. In CI core libraries like custom MY_Loader’s and controllers go into the core folder not libraries.
How is what the author has done in relation to extending the core class different than what the documentation says? I’m not really a CI expert, but I do know it pretty well and I can’t see any issues with how the author extends the CI_Loader core class.
edzjins,
As Code Junkie has “kindly” said you must be using Codeigniter 2.0. The guide you were viewing is for the latest version of Codeigniter which is 1.7.2 or was it 1.7.3? I don’t remember. You can get Codeigniter 2.0 from this url: http://bitbucket.org/ellislab/codeigniter/ – it’s stable, so don’t worry.
I’ve also added an update log to this post as well and soon will be adding a version without Smarty bundled.
Yes, all I had to do was an epic facepalm when I realised I’ve been trying to set it up for CI 1.7.3, sorry for wasting your time with that 🙂 Really, didn’t mention that as it was quite late and my brain couldn’t figure that out.. Gonna set it up for CI 2.0 now, and post the result when done. Thanks again for your responses though!
Hi, first of all thanks for creating this simple way to integrate Smarty 3 in CI 2. I have a question about using your method in combination with for example the form helper .
When I put this in the view it will be hardcoded in the source of the file. Is there another approach to achieve this?
Thanks in advance for your reaction.
@crimsun,
This library will work with Codeigniter 1.7.2 or 1.7.3 just by moving a couple of files. The examples are extending CI_Controller and CI_Model inline with the new Codeigniter 2.0 changes, so changing them to extend Model and Controller will make the examples work.
Moving MY_Loader from the core directory inside of the zip file to your Libraries folder and then placing the Smarty lib files inside of a folder called Smarty inside your libraries folder and changing the include path to reflect the new location of the Smarty files.
@Truth BeaRAWR!,
Dude, take a chill pill. It’s just the Internet, calm down.
@Go-Trex,
You can use helper functions inside of your views b placing the function inside of the curly braces. For example to the use form open helper function in your Smarty files simply do the following:
{form_open(‘controller/example_function’)}
This goes for any other functions as well. If you want access to the Smarty object I would store an instance in a variable called CI and pass that to the view so you can do things like $CI->config->item(‘itemname’), etc.
Hi Dwayne,
Thanks for your reaction. The helper part is clear to me but for example in the welcome_message.php file there is `elapsed_time` You mentioned something about storing an instance in a variable called CI which would be $CI = & get_instance() in the contructor I think.
When I modify elapsed_time to {$CI->elapsed_time} I’m still getting an error. Is this not what you meant in the previous comment?
Hi Go-Trex,
For this I have a MY_Controller which basically sets up some info to pass through to my views when needed. Here is how I do it:
$this->data[‘CI’] = &get_instance();
$this->data[‘elapsed’] = $this->data[‘CI’]->benchmark->elapsed_time(‘total_execution_time_start’, ‘total_execution_time_end’);
$this->data[‘memory’] = ( ! function_exists(‘memory_get_usage’)) ? ‘0’ : round(memory_get_usage() / 1024 / 1024, 2) . ‘MB’;
Then I can pass $this->data to my views when loading them and then be able to display page loading and memory usage by using {$elapsed} and {$memory} inside of my views. For accessing other CI stuff, I use: {$CI->whatever}
Thanks for your reaction, it’s very clear to me now. I’ve changed the welcome_message.php to this:
public $CI;
function __construct()
{
parent::__construct();
$this->CI = &get_instance();
}
function index()
{
$data[‘elapsed_time’] = $this->CI->benchmark->elapsed_time(‘total_execution_time_start’, ‘total_execution_time_end’);
$this->load->view(‘welcome_message’, $data);
}
I did not use a MY_Controller.
@Go-Trex,
Fantastic, glad you worked it out. If you plan on needing access to the CI instance inside of multiple views I recommend you use a MY_Controller otherwise you’re violating DRY in your controllers by repeating the same piece of code multiple times every time you want to access the Smarty instance.
Hi Dwayne,
Could you give a quick example on how to achieve this you mentioned in your last comment. I think more readers of your blog would love to know how to extend it a bit more further so to autoload your way to integrate Smarty 3 and see the welcome_page without any errors like it is now when autoloading your method.
Thanks in advance for your reaction again.
Fantastic, glad you worked it out. If you plan on needing access to the CI instance inside of multiple views I recommend you use a MY_Controller otherwise you’re violating DRY in your controllers by repeating the same piece of code multiple times every time you want to access the Smarty instance.
Hi Dwayne,
Thanks for your reaction. Could you explain in a small blog post or reaction how to use a MY_Controller in combination with your Smarty 3 integration method. I think more readers of your post would find it handy to know how this works without violating DRY. For example could you make the welcome page without any Smarty 3 erros given because ‘elapsed_time’ is nog Smarty variable of passed trough variable.
Thanks in advance for your reaction and keep up the good work!
Looks like the CI 2.0 branche is removed from http://bitbucket.org/ellislab/codeigniter. Is there another place available to download the CI 2.0 branche?
Go-Trex,
Codeigniter 2.0 is still on the repository, under the branches dropdown at the top select ‘tip’ and that is the current development version of CI 2.0. Mercurial is one confusing beast, don’t be alarmed seeing changes for CI 1.7.3 and whatnot as they don’t apply to the tip branch.
Just used this library. Fast install and flawless. Thanks very much! 🙂
Great utility, Dwayne, thanks. I made an addition My_Loader:
function assign() { // pass-thru to Smarty assign
$CI = & get_instance(); // Get instance of the Codeigniter object
$CI->load->library(‘smartyp’); // Load our Smarty parser library
call_user_func_array(array($CI->smartyp, ‘assign’), func_get_args());
}
Which allows you to assign data the same way you do in Smarty, which is sometimes easier than building up a big $data variable and passing it. You also get the cache control and the flexibility to pass pairs or arrays, e.g.
$this->load->assign(‘title’, “Page Title”);
$this->load->assign(array(‘h1’=>”Content Header”, ‘body’=>”Item Description Here”));
$this->load->view(“item.html”);
Is this the best place to post things like this? I think I saw a forum about this library, that might be better for a discussion, especially since this is not a particularly friendly thread (can you delete the inappropriate comments, they’re distracting).
Tac
Thanks for the addition Tac. I’ll implement the additions when I get a chance too, but to anyone else reading the comments your additions will help until I’ve added them in. I’ll also delete the bad comments, great suggestion.
hello thanks so much for your library,
but i have a question , how can i load a view file from the view folder
or a language variable or config variable?
$this->config->item(‘foo’);
$this->lang->line(‘foo’);
can i do this
{$this->lang->line(‘foo’)}??
Unfortunately the easiest way to do this is to set up some variables in your controllers like so:
$data[‘config’] = $this->config;
$data[‘lang’] = $this->lang;
Then pass through the $data variable when loading your Smarty view.
I haven’t tested, but that should work. Then you should be able to go in your Smarty views:
{$config->item(‘foo’)} and so on. It should work, if not you can always pass through the CI object by reference to your views as $CI and then use $CI instead of $this in your views.
thanks very much it work fine now
Is there anyway that you can switch between CI’s native view function, just having pure PHP in your view files, and then having Smarty view files?
Michael,
What do you mean? Do you mean that you want to have PHP view files and Smarty view files? Why can’t you just put PHP code in your Smarty views?
@Michael
I would also like to use both Smarty & CI views.
Changing the MY_Loader function name to view_smarty() rather than overriding the native view() seems to work for me although I have only run a simple test so far.
Separating the Smarty view files with .tpl also saves confusion (and makes syntax highlighting easier in my ide).
Thanks Dwayne, this library is really helpful!
I get a lot of Permission denied errors.
The official Smarty doc tells me to create the following dirs:
$> mkdir smarty/templates
$> mkdir smarty/templates_c
$> mkdir smarty/cache
$> mkdir smarty/configs
$> chown nobody:nobody smarty/templates_c
$> chown nobody:nobody smarty/cache
$> chmod 775 smarty/templates_c
$> chmod 775 smarty/cache
Could you tell me where to put them exactly? Into the root dir or into the third_party dir?
Owen,
Yep. Renaming the function in the MY_Loader to view_smarty() will still work fine and you shouldn’t notice any issues. I might add a config option to allow you to switch this on and off perhaps.
Raffael,
I have updated the post with a link to the repo this library is now hosted on. If you look inside of the download, you should see the cache directories are now all set up and you might just have to set the permissions on them.
The cache directories by the way go into application/cache
A PHP Error was encountered
Severity: Warning
Message: mkdir(): Permission denied
Filename: sysplugins/smarty_internal_write_file.php
Line Number: 28
A PHP Error was encountered
Severity: Warning
Message: rename(/tmp/wrtkm2VMJ,/home/lev/public_html/ci2/system/cache/smarty/compiled/a11c158f07695acc0868baf9a1e2cda542f0cba7.file.smartytest.php.php): No such file or directory
Filename: sysplugins/smarty_internal_write_file.php
Line Number: 48
A PHP Error was encountered
Severity: Warning
Message: chmod(): No such file or directory
Filename: sysplugins/smarty_internal_write_file.php
Line Number: 50
I changed the permissions of the /application/ directory to 777 but still got these errors. I moved all files and directories to the corresponding place in ci2 and autoloaded the “smarty” library.
Now it works. I changed the permissions of /system directory writeble.
Great work!
Works fine.
I have the need of good formvalidation. And have been searching a lot on the web, about smarty, validation, codeigniter, jquery and so on but many of the results are verry old, or they are verry complicated.
I would like to have a pretty simple way to achieve this, just add requirements and/or the range and so tho the smarty template. And then it should work. The best would be if I got an ajax validation that check the inputfields and so when the user is typing or clicking.
Do you or anyone else has any recomendation to some tool or plugin that does this.
regards Andreas
I forgot but thank you for this great work @Dwayne.
Is there something you / I can do with error handling?
If something happens now I get a nasty [i]Uncaught exception ‘SmartyException’ with message[/i] message.
Error Handling,
Maybe if you typed a descriptive and coherent answer, Dwayne might be able to answer you properly… http://www.dictionary.com
@Error handling – Are you talking about Smarty throwing errors for variables that don’t exist? Simply set the value of Smarty to not show exceptions and your errors should vanish. “$this->exception_handler = null;” throw that into the constructor of the CI_Smarty library in the libraries folder.
The latest build on github needs an update for it to work properly.
/libraries/MY_Parser.php : line 51
– $this->smarty->assign($key, $val);
+$this->ci->smarty->assign($key, $val);
Cheers!
Is possibile with this library use two different theme. Can i switch it from a controller with a set->theme for example….
Thans
vincenzo,
This library is merely for rendering the templates, it doesn’t have theming capabilities that part is up to you. With a few modifications Phil Sturgeon’s template library should work with it quite fine or with any templating library for Codeigniter that has parser support.
I don’t know how, have you got a wiki about it…
Thanks
Vincenzo,
Go here for Phil’s templating library: http://getsparks.org/packages/template/show – it supports themes and layouts, etc. With some modification (maybe) you can make it work with this library too. If this is a requested enough feature, I’ll implement true support into the library.
Hi Dwayne,
Really GR8 work! Minimal Configuration!
Mr,Dwayne.. what a great job you did.. Codeigniter and Smarty that is a “waaoow” combination.. Thanx to you people that we can enjoy codeigniter. God bless yi.
$this->parser->parse(“somepage.tpl”);
outputs as follows before template processing
A PHP Error was encountered
Severity: Warning
Message: Missing argument 2 for MY_Parser::parse(), called in somepage_controller.php on line 6 and defined
Filename: libraries/MY_Parser.php
Line Number: 22
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: libraries/MY_Parser.php
Line Number: 44
A PHP Error was encountered
Severity: Warning
Message: array_merge() [function.array-merge]: Argument #1 is not an array
Filename: libraries/MY_Parser.php
Line Number: 44
—
It seems some arguments like $data are missing in controller, but I just want to parse a couple of templates without passing variables like I do with other template engines such as Dwoo. Any clues how to overcome these warnings?
Dwayne, please check CI library of Dwoo’s template engine
http://forum.dwoo.org/viewtopic.php?id=119 -> ci_dwoo_1_0_2.zip -> Dwootemplate.php
as well as Seldaek’s comment in thread about ampersand near $CI = get_instance().
As you can see, library Dwootemplate.php is neither split into two files (MY_parser+Smarty), nor it requires $data argument obligatory. Could you be so kind and take best of it into your Smarty3 adapter for CodeIgniter?
Hi Dwayne,
I just wanted to thank you for a great Smarty-CI integration solution. Installation was very smooth, just one bug(!?I think!).
$this->ci = CI_Base::get_instance();
doesn’t work.
$this->ci = & get_instance();
works. Not sure what’s the difference b/w two methods. Thanks once again.
–
Anks
Not sure if everyone knows this already, but Dwayne has made a library for Codeigniter called Plenty Parser which is driver based and lets you render views using Twig or Smarty, it’s friggin’ amazing.
https://github.com/Vheissu/Plenty-Parser