A simple template engine
There are many template engines freely available for php, so many in fact that it can be overwhelming figuring out which one to use. During my journey of trying to find a template engine that I liked, I found a lot of debate about the usefulness of template engines that use their own template languages. After researching this for a while, I decided the best course of action would be to write my own that was template language free.
For those of you wondering why I didn’t just use smarty, it’s far more than just a template engine (Is smarty right for me?) Smarty to me is a template engine with a light controller that I don’t need. I normally write my own controllers to ease the integration of multiple open source projects.
A good read on why not to use template languages can be found here. He presents a template class that is really close to what I wanted but it uses php4 and includes caching. Caching is a wonderful tool, but like anything else it can be over used. Its biggest gains are had with caching of full pages which is best done by your controller.
This class was written using php5 magic methods. The only feature added that isn’t pure Templating is default values. Normally when you create a template you set some values and then execute it. I added the ability to pass override values to the execute function. This allows for some more general controller structures and less code in your templates.
To use this template class save your html as a php file. These template files are just normal html with inline php code except they are included inside of objects. All this means is that you have to use $this-> to access any variables you pass. For example in main.php from my below example I would print out someText like this. <?php echo $this->someText; ?> and in order to execute the left menu template I would write this <?php $this->leftMenu(); ?>
The source code for this template class is licensed under the MIT license.
Source code Download Here.
A small example. Please see the source code for documentation.
include_once(’template.php’);
$main = new Template(’main.php’);
$main->someText = ’some text’;
// loads leftMenu.php and saves it to $main->leftMenu;
$main->leftMenu();
// as above except it also sets $main->rightMenu->title = ’some template’;
$main->rightMenu(array(’title’ => ’some template’));
// how to call a template something different.
$main->bottomMenu = new Template(’leftMenu.php’);
$main->execute();
Category: Code Snippets












September 26th, 2007 at 8:29 am
great code. thank you mark