Example 7.30. A simple {foreach} loop <?php
$arr = array('red', 'green', 'blue');
$smarty->assign('myColors', $arr);
?>Template to output $myColors in an un-ordered list <ul>
{foreach $myColors as $color}
<li>{$color}</li>
{/foreach}
</ul>The above example will output: <ul>
<li>red</li>
<li>green</li>
<li>blue</li>
</ul>
----------------------------------------------------------
Example 7.31. Demonstrates the an additional key variable <?php
$people = array('fname' => 'John', 'lname' => 'Doe', 'email' => 'j.doe@example.com');
$smarty->assign('myPeople', $people);
?> Template to output $myArray as key/value pairs. <ul>
{foreach $myPeople as $value}
<li>{$value@key}: {$value}</li>
{/foreach}
</ul> The above example will output: <ul>
<li>fname: John</li>
<li>lname: Doe</li>
<li>email: j.doe@example.com</li>
</ul>
-------------------------------------------------------
Example 7.33. Database example with {foreachelse} <?php
include('Smarty.class.php');
$smarty = new Smarty;
$dsn = 'mysql:host=localhost;dbname=test';
$login = 'test';
$passwd = 'test';
// setting PDO to use buffered queries in mysql is
// important if you plan on using multiple result cursors
// in the template.
$db = new PDO($dsn, $login, $passwd, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$res = $db->prepare("select * from users");
$res->execute();
$res->setFetchMode(PDO::FETCH_LAZY);
// assign to smarty
$smarty->assign('res',$res);
$smarty->display('index.tpl');?>
?> {foreach $res as $r}
{$r.id}
{$r.name}
{foreachelse}
.. no results ..
{/foreach}