11.13. Using Smarty Templates11.13.1. ProblemYou 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. 11.13.2. SolutionUse 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. DiscussionHere'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. 11.13.4. See AlsoThe Smarty home page at http://smarty.php.net/. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|