Prev | Current Page 558 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Consider two examples. The first involves iteration over a simple indexed array:
$smarty = new Smarty;
$titles = array(
"Pro PHP",
"Beginning Python",
"Pro MySQL"
);
$smarty->assign("titles",$titles);
$smarty->display("titles.tpl");
The titles.tpl template contains the following:
{section name=book loop=$titles}
{$titles[book]}

{/section}
This returns the following:
Pro PHP

Beginning Python

Pro MySQL

Note the somewhat odd syntax, in that the section name must be referenced like
an index value would within an array. Also note that the $titles variable name does
double duty, serving as the reference for both the looping indicator and the actual
variable reference.
Now consider an example using an associative array:
CHAPTER 19 ?–  TEMPLAT ING WITH SMARTY 489
$smarty = new Smarty;
// Create the array
$titles[] = array(
"title" => "Pro PHP",
"author" => "Kevin McArthur",
"published" => "2008"
);
$titles[] = array(
"title" => "Beginning Python",
"author" => "Magnus Lie Hetland",
"published" => "2005"
);
$smarty->assign("titles", $titles);
$smarty->display("section2.tpl");
The section2.tpl template contains the following:
{section name=book loop=$titles}

Title: {$titles[book].title}

Author: {$titles[book].author}

Published: {$titles[book].published}


{/section}
This returns the following:


Title: Pro PHP

Author: Kevin McArthur

Published: 2008



Title: Beginning Python

Author: Magnus Lie Hetland

Published: 2005


490 CHAPTER 19 ?–  T EMPLAT I NG WITH SMARTY
The sectionelse Function
The sectionelse function is used in conjunction with section and operates much like
the default function does for strings, producing some alternative output if the array
is empty.


Pages:
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570