International Developer Logo Last Updated 25.07.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Developing Three-Tier Web Applications with PHP


Daniel Winter   01.10.05


Although the PEAR library contains a couple of template libraries, each with their own pros and cons, the Smarty template engine offers some extra features such as caching and a range of add-ons and plugins. Smarty is a class library that parses HTML files for known Smarty markup tags before compiling a finished PHP file. These compiled pages can be cached, as can the actual HTML output, making Smarty particularly fast and efficient compared to templating systems that recompile the page with every request. To use Smarty, extract the archive to a Smarty directory and add it to the PHP includes parameter as per the PEAR instructions. The most basic configuration of Smarty requires the inclusion of the class file, the creation of a Smarty object, and the setting of four path parameters. Once that is done, you simply assign values to the Smarty object and call the display() method to render the page to HTML.

require('Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir  = '/web/templates';
$smarty->compile_dir  = '/web/templates_c';
$smarty->cache_dir  = '/web/cache';
$smarty->config_dir  = '/web/configs';
$smarty->assign('key', 'value');
$smarty->display('index.tpl');

The last two lines of this code tell the Smarty object to parse the index.tpl file and replace any instances of the value 'key' with the text 'value'. So, for instance, if the index.tpl file looks like this:

<html>
<body>
 {$key}
</body>
</html>
Then the HTML output will look like this:
<html>
<body>
 value
</body>
</html>

That's a template at its most basic level. Taking a step further, you can include other templates as well as embedding display logic into the Smarty markup. For instance, the following example will loop over an array called $students and display each name in a table row of an alternating colour.




   Previous Page  ... 11 12 Next Page   

HAVE YOUR SAY
This article is rated  Rate this article