Tuesday, 11 September 2007

Smarty Templates - PHP Presentation Framework

Smarty templates can help to separate php coding from presentation. So, your code looks clean and tidy while the HTML templates are much easier to maintain. The beauty of it is that designers don't break your application code and you never messing with templates.

It is more like to put your php code on a layer beneath its presentation and keep a same logic.
Here is an example explaining how I use smarty:

Step One: Specify the smarty template file structure:
Create a folder named smarty under /home/www, and then create 4 sub-folders as named in the php file below. Make sure you change the file permission to 0777 on the templates_c folder.

require_once('/usr/local/lib/php/Smarty/Smarty.class.php'); //Download it from smarty.org
class zSmarty extends Smarty {
public function __construct () {
$this->template_dir = '/home/www/smarty/templates';
$this->compile_dir = '/home/www/smarty/templates_c';
$this->cache_dir = '/home/www/smarty/cache';
$this->config_dir = '/home/www/smarty/configs';

Step Two: PHP Code

require_once ("zSmarty.php"); //include smarty template class
$ztpl = new zSmarty(); //create smarty template object
assign('name', "Alex"); //assign a value to {$name} which is on the
$ztpl->display('test.tpl'); //display the template

Step Three: Template File (test.tpl)
Store test.tpl in /templates folder.


Name: {$name}

If you want to place javascript on your templates, please use {literal} tags. For example:

{literal}<script>... </script>{/literal}

No comments: