PHP DevCenter
oreilly.comSafari Books Online.Conferences.


Introducing Smarty: A PHP Template Engine
Pages: 1, 2, 3

Some Real-World Examples

One of my favorite ways to use Smarty is to develop my applications with PEAR::DB and have templates take care of the layout formatting. Most of my applications nowadays are full of instances of the following:

include_once('DB.php'); // include PEAR::DB class
$db = DB::connect();

$stmt = "SELECT name, last_name FROM users";

// returns a nested associative array
$users = $db->getAll($stmt, DB_FETCHMODE_ASSOC); 

$tpl = new Smarty;

$tpl->assign('users', $users);

And the appropriate index.tpl would be:

{section name="i" loop=$list}
  <b>Name: {$list[i].name}; Last Name: {$list[i].last_name}</b><br>
  <b><br>Array $list has no entries</b>

Smarty is so convenient and easy to use that it almost makes me sad thinking about all the time I used to spend doing set_var(), parse(), and etc when I used to use PHPLIB-based templates.

Another good example of how Smarty makes your life easier is the collection of built-in custom functions that come with it.

A simple yet very convenient set of functions is the {html_options}, {html_select_date}, and {html_select_time} tags. With these functions you don't need to worry about constructing HTML select boxes in your PHP code. Rather, you can leave that boring task to Smarty, and it will format the output the way you wanted:

<select name="player_id">
	{html_options options=$players selected=$current.player_id}

With the template above all you need to do in your PHP code is the following:

$tpl = new Smarty;

$players = array(
    "23" => "Michael Jordan",
    "32" => "Michael Johnson"
$tpl->assign('players', $players);

$current_player = array(
    "player_id" => "23",
    "name" => "Michael Jordan"
$tpl->assign('current', $current_player);


In my next article, I'll get to more in-depth coverage of the available features on Smarty as well as more examples of how to make the most out of it. See you then.

Joao Prado Maia is a web developer living in Houston with more than four years of experience developing web-based applications and loves learning new technologies and programming languages.

Return to PHP DevCenter.

Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!

Sponsored by: