Prev | Current Page 556 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

tpl");
The states.tpl template contains the following:
{foreach key=key item=item from=$states }
{$key}: {$item}

{/foreach}
This returns the following:
OH: Ohio
CA: California
NY: New York
Although the foreach function is indeed useful, you should definitely take a moment
to learn about the functionally similar yet considerably more powerful section function,
introduced in this section.
CHAPTER 19 ?–  TEMPLAT ING WITH SMARTY 487
The foreachelse Function
The foreachelse function is used in conjunction with foreach, and operates much
like the default tag does for strings, producing some alternative output if the array is
empty. An example of a template using foreachelse follows:
{foreach key=key item=item from=$titles}
{$key}: $item}

{foreachelse}

No states matching your query were found.


{/foreach}
Note that foreachelse does not use a closing bracket; rather, it is embedded within
foreach, much like an elseif is embedded within an if function.
The section Function
The section function operates in a fashion much like an enhanced for/foreach, iterating
over and outputting a data array, although the syntax differs significantly. The
term enhanced refers to the fact that it offers the same looping feature as the for/foreach
constructs but also has numerous additional options that allow you to exert greater
control over the loop??™s execution.


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