I’m deep in the midst of the forum I’m creating (more updates about it to come later) and I decided to implement Smarty into it since I’m considering releasing it for distribution at some point, and my target users would definitely be more comfortable with {$var} than <= $var; ?> or <php echo $var; ?> .
The one thing snagging me was how to incorporate a layout so I didn’t end up with 100+ template files that had the {include file=”header.tpl”} in them. Definitely a PITA and not that great if you want more flexibility.
With a little bit of trial and error, I created a library that is less than 50 lines long, works awesomely with Smarty and supports layouts.
Instructions
1. Download the latest version of Smarty from http://www.smarty.net
2. Extract the /libs folder to your application/libraries folder and rename to smarty
3. Open your favorite text editor and put the code found @http://codesnippets.joyent.com/posts/show/1966 into it.
Save as Template.php in your application/libraries folder. In the __construct() function, change the paths to suit your application. For me, I chose to place my templates folder above my application folder, and the other folders within the /smarty folder. You can also change the template extension in the layout function to something other than .tpl, if you like.
3b. If you want to load this application-wide, open up your config/autoload.php file and add “template” to the libraries array.
4. Next, create a default.tpl (or default.html, etc) file and where you would like the content displayed, put the following:
{include file="$inner_template.tpl"}
(again, you can change the tpl to something else if you wish). Save this to your templates folder.
5. To use, load the template library and then use it like so:
$this->template->layout("content_template", array("array"=>"of stuff","to"=>"use within the template"));
6. If you want to use a different layout for part of your app, simple include the following line before calling the $this->template->layout function:
$this->template->theme = "other_layout_name";
There may be better ways to do this, and I know a lot of programmers absolutely loathe template engines and will argue til the sun comes up that they serve no useful purpose and everyone should stick with pure php. However, this particular method is working very well for me and my program 🙂