PART II
Chapter 9: Site and Application Architecture with Ajax 435
{else}
<span>Boring</span>
{/if}
Simple loops can be performed with the {foreach} construct. For example, looping
over a wrapped JSON array like {"stooges" : ["Larry","Curly","Moe"]}, a list can
easily be produced from a template:
<ul>
{foreach from=$stooges item=stooge}
<li>{$stooge}</li>
{/foreach}
</ul>
Potentially more useful with typical JSON packets would be the associative array
looping. Given this small object that contains an array of objects:
{"stooges":[
{"name":"Larry", "line": "Hey Moe!"},
{"name":"Curly", "line": "Nyuck nyuck nyuck"},
{"name":"Moe", "line": "Why I outta!"}
]
}
The {foreach} can be used to loop over the values and output them into a table:
<table border="1" cellpadding="3" cellspacing="3" width="400px">
{foreach item=stooge from=$stooges}
<tr>
<td>{$stooge.name}</td>
<td>{$stooge.line}</td>
</tr>
{/foreach}
</table>
which when rendered with data would produce:
<table border="1" cellpadding="3" cellspacing="3" width="400px">
<tr><td>Larry</td><td>Hey Moe!</td></tr>
<tr><td>Curly</td><td>Nyuck nyuck nyuck</td></tr>
<tr><td>Moe</td><td>Why I outta!</td></tr>
</table>
It may be necessary to include an {if} construct to address the situation when there is
no data. That is possible, but the {foreach} also provides a {foreachelse} construct
which would be called in the case there is no data to loop with:
<table border="1" cellpadding="3" cellspacing="3" width="400px">
{foreach item=stooge from = $stooges}
<tr>
<td>{$stooge.name}</td>
<td>{$stooge.line}</td>
</tr>