Monday, January 17, 2011

Using Smarty PHP Template Engine for Your Design Layer

Looking for a template engine for your latest web application? The good folks over at Smarty have got you covered.

I have been using Smarty for quite awhile now and it has been great. I won't go into all of the reasons I prefer it to some of the other options out there, but I will show you how to use it...

First, you need to download the source from the Smarty website: http://www.smarty.net/download

Now you are ready to get your hands dirty.

The PHP side will look something like this:

// first include the smarty library
include('Smarty.class.php');

// now we create the smarty object
$smarty = new Smarty;

// now we tell smarty where to look for template files
// and where to store compile/config/cache info
$smarty->template_dir = THEFULLPATH.'views/templates/';
$smarty->compile_dir  = THEFULLPATH.'views/templates_c/';
$smarty->config_dir   = THEFULLPATH.'views/configs/';
$smarty->cache_dir    = THEFULLPATH.'views/cache/';

// lets assign our data to template variables now
// in real life you would be getting this data
// from user input or a database, but here we
// are just using a static value
$smarty->assign('FullName', 'Jon Doe');

// display the template
$smarty->display('mytemplate.tpl');

Not bad so far ... now lets create the actual template:

<html>
   <head>
      <title>Hello World</title>
   </head>
   <body>
      Hello {$FullName}
   </body>
</html>

As you can see, Smarty is pretty simple to use. If you would like to become a Smarty expert, a good place to start is here: http://www.smarty.net/crash_course

No comments:

Post a Comment