Loop statements provide a means to iterate through a list of collections. Additional variables specific to loops also become available within the structure as is a syntax to exit a loop prematurely. Collection lists are a common website template variable construct so let's go over them again.
A collection and it's keys, often referred to as a record-set, are accessed differently and requires the indication of a key name. Keys are indicated through brackets and optional quotes enclosing the key name.
For example, a variable representing an account may have first and last name variables. These values can be accessed as myAccount['FirstName'] or myAccount['LastName']. You can use single, double or no quotes so myAccount['FirstName'] is the same as myAccount["FirstName"] and myAccount[FirstName].
Let's look at the syntax, a loop consists of two parts which are the variable and collection and are defined as { [ VARIABLE ] in [ LIST ] } ... { loop } where VARIABLE is the name of a variable and LIST is the list of collections to iterate over.
{ myAccount in accounts }
<div>{ myAccount['FirstName'] } { myAccount['LastName'] }</div>
{ loop }
In this example, accounts is your collection list and myAccount is assigned a single collection for each iteration. Data is accessed using a collection variable.
The loop syntax introduces a couple variables which adds additional control over it's behavior. These are standard variables and only available within the loop structure, and consists of iteration, first and last.
Note: Special variables are in lower case.
The iteration variable holds the current iteration number of a loop, starting at 1. It can be used to add counts to your list or combined with first and last. The first and last variables are assigned numerical values related to iteration. Last is a number representing the last iteration of a loop while first is the opposite. We'll introduce an example later.
There is one special syntax specific to loops and it's called leave represented as { leave }. The leave syntax forces the loop to stop iterating over a list once encountered, that is, provides a way to stop iterating.
Let's take a look at the previous example with special variables and the leave statement implemented.
{ myAccount in accounts }
<div>{ interation } )</div>
<div>{ myAccount['FirstName'] } { myAccount['LastName'] }</div>
{ interation = last }
</hr>
{ end }
{ interation = 3 }
{ leave }
{ end }
{ loop }
There are a few things to look at here
- The iteration variable is used as a counter for account records.
- Iteration is compared to the last iteration and if positive, a line is added.
- If iteration evaluates to 3 then the loop is stopped.