2.7.12. Foreach

Another loop that iterates through an array or object and passes the element index and value to the template variables. Like in PHP, it takes three parameters:

Table 2.11. Foreach: parameters

Foreach: parameters
NameTypeRequired?Description
tableExpressionYesThe array or object we want to iterate through.
indexIDYesIndex variable name.
valueIDYesValue variable name.
separatorExpressionNoA separator inserted between two section elements. The parameter can be replaced with the separator instruction. The parameter is available since OPT 1.1.3.

Example 2.59. Foreach and arrays

{@array is array(
 'Name' => 'John',
 'Surname' => 'Smith',
 'Age' => 31
)}

<table>
{foreach=@array; title; value}
<tr>
<td>{@title}</td>
<td><input type="text" name="{@title}" value="{@value}"/></td>
</tr>
{/foreach}
</table>

This instruction can be used with separators.

OPT variant of foreach supports also {foreachelse} block. Its content is presented, if the parsed array/object contains no elements:

Example 2.60. Foreachelse

<table>
{foreach=$array; title; value}
<tr>
<td>{@title}</td>
<td><input type="text" name="{@title}" value="{@value}"/></td>
</tr>
{foreachelse}
<tr>
<td colspan="2">Please specify the form data!</td>
</tr>
{/foreach}
</table>