Lists

A list structure looks like this:

<list listExpression as indexVariable>
    Some HTML...
</list>
	

Or like this:

<foreach indexVariable in listExpression>
    Some HTML...
</foreach>
	

The structure iterates through the items in the list referred to by listExpression. Within the loop body, indexVariable is used to refer to each element of the list in turn. (The index variable acts as a local variable; any value it has outside the loop is hidden within the loop body.) The list structure is particularly useful for building HTML tables using dynamic data. For example:

<table border="1">
    <tr>
        <td>Date</td>
        <td>Amount</td>
    </tr>
    <list deposits as deposit>
        <tr>
            <td>${deposit.date}</td>
            <td>${deposit.amount}</td>
        </tr>
    </list>
</table>
	

Since lists can be nested, you can make tables that have a variable number of rows and columns. For example:

<table border="1">
    <list rows as cells>
        <tr>
            <list cells as cell>
                <td>${cell}</td>
            </list>
        </tr>
    </list>
</table>
</fm_code>
<p>
In FreeMarker Classic, if you gave a scalar as the list value, it would be 
treated as a list with a single element. This no longer works in FreeMarker 2,
but there is a simple workaround. You can simply define a one-element list
explicitly.
</p>

<fm_code><![CDATA[
<assign y=[x]>
<foreach item in y>
   blah blah ${item} 
</foreach>
	

Loop counter

You can access the loop counter (the number of times a list has iterated so far) using the item_index syntax where "item" is the name of the loop control variable. Assume you want to create a numbered list of items; you can use:

<foreach color in rainbow>
    ${color_index + 1}. ${color}
</foreach>
	

Note we add 1 to the index since it starts at zero, and we want our list to start at 1.

"has-next" indicator

In a similar fashion, you can use the item_has_next syntax to determine if there will be more iterations or not. Assume you want to create a common English sentence that enumerates the colors of the rainbow:

Rainbow consists of
<foreach color in rainbow>
  <if !color_has_next>and</if>
  ${color}
  <if color_has_next>, <else>.</if>
</foreach>
	

Breaking out of a loop

As of the second Lazarus release, you can use the <break> directive to break out of a loop.