Looping
If you were an assembly line worker, your job might be to repeat a set of steps over and over again throughout the day. If you installed the rearview mirror on the windshield, you would perform the same steps for installing each one. You would perform these steps until your shift ended and then you'd go home for the day. This process might contain the following steps:
Step 1 Car arrives to your station
Step 2 Take rearview mirror from its packing
Step 3 Measure windshield to determine middle of width
Step 4 Affix rearview mirror with adhesive
Step 5 Test that the mirror is working properly
You would repeat each of these steps for every car that comes to your station until your shift was over.
The <CFLOOP> Tag
Looping in the programming world is similar because it allows you to repeat a set of instructions or display output over and over until one or more conditions are met. The <CFLOOP> tag allows you to create programming loops in CFML. This tag has an opening and closing tag, with the instructions you want to perform multiple times enclosed within the tags:
<CFLOOP ..> HTML or CFML code to loop over ... </CFLOOP>
<CFLOOP> supports five different types of loops:
Looping over a list
Index loops
Condition loops
Looping over a query
Looping over a structure
The type of loop is determined by the attributes of the <CFLOOP> tag. You won't understand the last two types of loops (query and structure) until you learn about those concepts.
NOTE
You will be learning about structure loops in Hour 18, "Using Advanced Variable Types."
Looping over a List
As an example of a loop list, you can take a list of colors and display them in table cells:
<TABLE BORDER="1"> <TR> <CFLOOP INDEX="MyColor" LIST="red,blue,silver" DELIMITERS=","> <CFOUTPUT> <TD BGCOLOR="#MyColor#"> <B>#MyColor#</B> </TD> </CFOUTPUT> </CFLOOP> </TR> </TABLE>
Figure 6.5 depicts the output of this code.
Figure 6.5 This output is generated by looping through a list of colors and printing them into table cells.
Wrapping Code
Notice my <CFLOOP> tag and its attributes are each on separate lines and nicely aligned. I was able to get HomeSite to do that for me through the Tag Dialog for <CFLOOP>. To do this yourself, position yourself on top of the <CFLOOP> tag and choose Edit Tag. The dialog has a checkbox at the bottom that enables you to turn off the Output on a single line option. This helps your code be more readable.
We will now dissect this code. Inside the <TR> tag, you see a <CFLOOP> tag. This tag has a few attributes:
INDEXThis attribute holds the value of each item in the list as the loop steps through the list.
LISTA comma-separated list of values; in this case, "Red,Blue,Silver".
DELIMITERSSpecifies the character that separates each list value; in this case, the comma (,).
For each value in the list, it will execute the following code:
<CFOUTPUT> <TD BGCOLOR="#MyColor#"> <B>#MyColor#</B> </TD> </CFOUTPUT>
This will take each color value and use it for the background color of the <TD> tag as well as print out the name of the color. The <CFOUTPUT> tag specifies that the variables need to be resolved to their values. This yields a three-column table with one row because there are three values in the list.
This loop, known as a list loop is used to execute code a number of times equal to the number of values in the list.
TIP
Lists are extremely important to ColdFusion Express developers because the comma delimited list format is used by HTML (for form submissions) and SQL (in IN operators). As such, ColdFusion Express provides a whole family of functions specifically for use in manipulating lists. We'll look at lists in detail in Hour 18.
Using the Index Loop
The index loop allows you to iterate code based on a series of numeric values. To loop ten times and print out the loop number, you would use the following code:
<CFLOOP INDEX="i" FROM="1" TO="10" > Loop number: <CFOUTPUT>#i#</CFOUTPUT><BR> </CFLOOP>
When this loop is first started, the index variable i (INDEX attribute) is set to the initial value of 1 (FROM attribute). It will go through the following process:
Executes the code inside the <CFLOOP> tag to print out the string "Loop number: 1".
Returns to the opening <CFLOOP> tag and increments INDEX to 2.
Executes the code inside the <CFLOOP> tag to print out "Loop number: 2".
This process is repeated until it goes through the loop for the last time with a value of 10. The output is as shown in Figure 6.6.
Figure 6.6 This index loop will iterate 10 times.
The full syntax of the <CFLOOP> tag for an index loop is shown as follows:
<CFLOOP INDEX="IndexVariable" FROM="StartValue" TO="EndValue" STEP="Increment"> </CFLOOP>
Notice that there is a STEP attribute to this tag. The default is to increment by 1 from the FROM value to the TO value. You can change the increment value by using the STEP attribute. For instance, you can increment by 2:
<CFLOOP INDEX="i" FROM="1" TO="10" STEP="2"> The loop index is <CFOUTPUT>#i#</CFOUTPUT><BR> </CFLOOP>
This loop will only execute five times, as the output in Figure 6.7 illustrates.
Figure 6.7 This index loop will iterate five times, stepping by 2.
The STEP attribute can also take a negative value, if you want to count backwards. For instance, you can decrement by 1:
<CFLOOP INDEX="i" FROM="10" TO="1" STEP="-1"> The loop index is <CFOUTPUT>#i#</CFOUTPUT><BR> </CFLOOP>
This loop will only execute 10 times, but will count backwards as the output in Figure 6.8 illustrates.
Figure 6.8 This index loop will iterate 10 times counting backwards.
Looping on a Condition
Whereas the index loop iterates by numeric values, the conditional loop will iterate until a condition is no longer TRUE (becomes FALSE) .
In this loop, you need to determine which condition you want to test, and that condition must yield a TRUE or FALSE outcome.
In the following code example, you will begin by initializing a CountVar variable to 0, and you will test and increment that variable until it exceeds a value of 10:
<!--- Set the variable ConditionVariable to 0 ---> <CFSET ConditionVariable=0> <!--- Loop until ConditionVariable = 10 ---> <CFLOOP CONDITION="ConditionVariable LESS THAN OR EQUAL TO 10"> <CFSET ConditionVariable=ConditionVariable + 1> The ConditionVariable is <CFOUTPUT>#ConditionVariable#</CFOUTPUT>.<BR> </CFLOOP>
Notice in this example that the loop will run 11 times, as Figure 6.9 shows. This loop executes 11 times because it is counting from 0 to 10, inclusive, which is 11 times.
Figure 6.9 This conditional loop will iterate 11 times.
Does the logical operatorLESS THAN OR EQUAL TOlook familiar? It should. All the same operators that apply to the <CFIF> tag also apply to the conditional loop.
CAUTION
Don't forget that all loops must come to an end. If you incorrectly form your condition, it might never reach a FALSE result and therefore will never end. If this happens, it's called an endless loop. Kinda like the directions on the shampoo bottlelather, rinse, repeatit never tells you when to stop.
Using <CFLOOP> to Create a Color Palette
We will look at an application of using the <CFLOOP> tag. To set this up, you must understand the colors available to the Web.
HTML has two ways to refer to colors, by name (for example, red or green), or by RGB value (for example, #FF0000 and #00FF00). The RGB value format is more powerfulit supports a far greater range of colors and far more browsers. This color palette is known as the Browser Safety Palette, which should be supported by most browsers.
To Do: Looping to Create the Browser Safety Palette
View the Browser Safety Palette in HomeSite by performing the following steps:
Launch HomeSite
On the main toolbar, choose the Palette option.
You will see the Browser Safety Palette as shown in Figure 6.10. Move the mouse over the colors, and you will see the hexadecimal value for each.
Figure 6.10 HomeSite's Browser Safety Palette can be displayed by choosing the palette toolbar item on the main toolbar.
The RGB number is made up of hexadecimal numbers from black (#000000) to white (#FFFFFF). You can build all the colors in between by using a combination of hexadecimal pairs00,33,66,99,cc,ff. If you combine each of these pairs with the others into six-digit hexadecimal numbers, you will find every RGB color available.
For instance, you can concatenate three pairs in this order:
00 & 00 & 00 = 000000 00 & 00 & 33 = 000033 00 & 00 & 66 = 000066 00 & 00 & 99 = 000099 00 & 00 & cc = 0000cc 00 & 00 & ff = 0000ff 00 & 33 & 00 = 003300 00 & 33 & 33 = 003333
If you were to continue and combine each pair with the other, all colors in the palette would be created. To do this, you can create three nested loops:
<CFSET hex="00,33,66,99,cc,ff"> <CFLOOP INDEX="Red" LIST="#hex#"> <CFLOOP INDEX="Green" LIST="#hex#"> <CFLOOP INDEX="Blue" LIST="#hex#"> <CFSET RGB=Red & Green & Blue> <CFOUTPUT>#RGB#</CFOUTPUT><BR> </CFLOOP> </CFLOOP> </CFLOOP>
Each of the three pairs of digits are concatenated together using the ampersand (&) into one RGB variable. Figure 6.11 shows some of the output for this code.
Figure 6.11 Nested loops can be used to construct strings.
Next we will use the generated RGB number as the background color of a table cell; one for each RGB number generated as shown in Listing 6.1.
Listing 6.1 Using CFLOOP to Produce the Browser Safety Palette
1:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 2: 3:<HTML> 4:<HEAD> 5: <TITLE>Using CFLOOP to produce the Browser Safety Palette</TITLE> 6:</HEAD> 7: 8:<BODY> 9: 10:<!--- set hex pairs ---> 11:<CFSET hex="00,33,66,99,cc,ff"> 12: 13:<!--- loop through each list of hex pairs---> 14:<TABLE> 15:<CFLOOP INDEX="Red" LIST="#hex#"> 16: <CFLOOP INDEX="Green" LIST="#hex#"> 17: <TR> 18: <CFLOOP INDEX="Blue" LIST="#hex#"> 19: <CFSET RGB= Red & Green & Blue> 20: <CFOUTPUT><TD BGCOLOR="#RGB#" 21: WIDTH="100" 22: ALIGN="center">#RGB# 23: </TD> 24: </CFOUTPUT> 25: </CFLOOP> 26: </TR> 27: </CFLOOP> 28:</CFLOOP> 29:</TABLE> 30: 31:</BODY> 32:</HTML>
Each color in the Browser Safety Palette is now displayed in a table, as shown in Figure 6.12.
Figure 6.12 You can create the Browser Safety Palette using three nested loops.
This is just one of the many reasons to use the <CFLOOP> tag.