home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

11.13. Using Smarty Templates

11.13.2. Solution

Use a templating system. One easy-to-use template system is called Smarty. In a Smarty template, strings between curly braces are replaced with new values:

Hello, {$name}

The PHP code that creates a page sets up the variables and then displays the template like this:

require 'Smarty.class.php';

$smarty = new Smarty;
$smarty->assign('name','Ruby');
$smarty->display('hello.tpl');

11.13.3. Discussion

Here's a Smarty template for displaying rows retrieved from a database:

<html>
<head><title>cheeses</title></head>
<body>
<table border="1">
<tr>
  <th>cheese</th>
  <th>country</th>
  <th>price</th>
</tr>
{section name=id loop=$results}
<tr>
  <td>{$results[id]->cheese}</td>
  <td>{$results[id]->country}</td>
  <td>{$results[id]->price}</td>
</tr>
{/section}        
</table>
</body>
</html>

Here's the corresponding PHP file that loads the data from the database and then displays the template, stored in food.tpl:

require 'Smarty.class.php';

mysql_connect('localhost','test','test');
mysql_select_db('test');

$r = mysql_query('SELECT * FROM cheese');
while ($ob = mysql_fetch_object($r)) {
    $ob->price = sprintf('$%.02f',$ob->price);
    $results[] = $ob;

}
$smarty = new Smarty;
$smarty->assign('results',$results);
$smarty->display('food.tpl');

After including the base class for the templating engine (Smarty.class.php), you retrieve and format the results from the database and store them in an array. To generate the templated page, just instantiate a new $smarty object, tell $smarty to pay attention to the $results variable, and then tell $smarty to display the template.

Smarty is easy to install: just copy a few files to your include_path and make a few directories. You can find full instructions at http://smarty.php.net/manual/en/installing.smarty.basic.html. Use Smarty with discipline to preserve the value of having templates in the first place — separating your logic and your presentation. A template engine has its own scripting language you use to interpolate variables, execute loops, and do other simple logic. Try to keep that to a minimum in your templates and load up your PHP files with the programming.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.