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:
<?php
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);
include_once('Smarty.class.php');
$tpl = new Smarty;
$tpl->assign('users', $users);
$tpl->display('index.tpl');
?>
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>
{sectionelse}
<b><br>Array $list has no entries</b>
{/section}
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}
</select>
With the template above all you need to do in your PHP code is the following:
<?php
include_once('Smarty.class.php');
$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);
$tpl->display('index.tpl');
?>
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.