11.12. Using Smarty Templates
Problem
You want to separate code and design in your pages. Designers can work on the HTML files without dealing with the PHP code, and programmers can work on the PHP files without worrying about design.
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');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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access