ForEach Loops
As of March 2017, Branch Code is deprecated and no longer developed. Use the Twig syntax instead.
The foreach loops let you loop through an array of data. This is one of the most commonly used pieces of Branch Code.
An example usage would be to loop through an array of product information to build a store product list page.
The tag could be a 'loop' tag or a 'foreach' tag. They both do the exact same thing, but the 'loop' version is most commonly used.
Below is a basic example.
{loop items='#items' value='item'}
{/loop}
or
{foreach items='#items' value='item'}
{/foreach}
Parameters
There are two parameters for the 'loop' tag.
Parameter | Description |
---|---|
items |
Description: The name of the variable that holds the array of items to be looped over. Note that curly brackets are not use. The # sign must be used. Type: String Required: Yes Example: items="#variableName" |
value |
Description: The name of the variable to use for the item inside the loop. Note that neither the curly brackets and the # sign are not used. Type: String Required: Yes Example: value="item" |
key |
Description: The name of the variable to use for the array key for each item side the loop. Type: String Required: No Example: key="key"
|
Examples
Example 1
The below example will loop through an array of store products and output a link to the product.
{loop items="#products" value="product"}
<p><a href="{#product.url}">{#product.productName}</a></p>
{/loop}
Example 2
The below example will loop through an array of gallery images. If the item is the first item then it's made bold.
{loop items="#items" value="item" key="key"}
{if #key == 0}
<p><strong>First Item: <a href="{#item.url}">{#item.itemName}</a></strong></p>
{else}
<p><a href="{#item.url}">{#item.itemName}</a></p>
{/if}
{/loop}