Repeating Text with #foreach

You can use the #foreach directive to loop through the same text multiple times.  For example:

 

<HTML>

<BODY>

Count to ten.<BR><BR>

#foreach( $number in [1..10] )
$number<BR>
#end

</BODY>

</HTML>
 

 

Produces the following output:

 

Count to ten.

1
2
3
4
5
6
7
8
9
10
 

 

This #foreach loop causes $number to be looped over for all of the products in the array [1..10]. Each time through the loop, the next element in the [1..10] array is placed into $number.

 

Using #foreach with Ranges of Numbers

The range operator can be used in conjunction with the #foreach statement. Useful for its ability to produce an object array containing integers, the range operator has the following construction:

[n..m]

Both n and m must either be, or produce, integers. Whether m is greater than or less than n will not matter; If m is less than n, the range will simply count down.

Simple examples showing the use of the range operator are provided below:

First example:
 

#foreach( $count in [1..5] )
$count
#end
 

 

Produces the following output:

 

1 2 3 4 5
 

 

Second example:
 

#foreach( $countdown in [2..-2] )
$countdown
#end
 

 

Produces the following output:

 

2 1 0 -1 -2
 

 

Third example:
 

#set( $arr = [0..5] )

#foreach( $i in $arr )
$i
#end
 

 

Produces the following output:

 

0 1 2 3 4 5
 

 

Using #foreach with Lists

You can define a List with the #set directive and loop through each item.  

For example, if the following model has been loaded into Broadcast:

 
V Sales = 121
V Profit = 71000
V Price = 1000
P Price.NumberFormat = "$#,##0"

M NumberFormat = "#,##0"

 

 

Then the following code:

 
<HTML>

<BODY>

#set ($VariableList = ["Sales", "Profit", "Price"])

#foreach ($VarName in $VariableList)
The value of $VarName is $Values.get($VarName).ResultFormatted<BR>
#end

</BODY>

</HTML>
 

 

Produces the following output:

 

The value of Sales is 121
The value of Profit is 71,000
The value of Price is $1,000
 

 

Listing all Variables in the Model:

Because $Values is a list of all the variables in your model, you can easily create a list of every variable in your model with the following code:

 

<HTML>

<BODY>

#foreach ($VarName in $Values)
$VarName.Label = $VarName.ResultFormatted<BR>
#end

</BODY>

</HTML>
 

 

Read more about lists in the following article:

Working with Lists