Looping
Looping allows you to repeat specific blocks
of code (both HTML and CFML) within your CFML templates. ColdFusion
supports a variety of looping constructs with the
<CFLOOP> tag, including index
(for) loops, conditional
(while) loops, collection loops, list loops, and
query loops. For now, we are just going to cover basic index and
conditional loops. Query loops are covered in Chapter 4, while collection and list loops are covered
in Chapter 6.
Index Loops
Also known as a for loop,
an index loop repeats a number of times specified as a range of
values:
<CFLOOP INDEX="index_name" FROM="number" TO="number" STEP="increment"> HTML and CFML... </CFLOOP>
The INDEX attribute of
the loop specifies a variable name to hold the value corresponding to
the current iteration of the loop. The FROM
attribute initializes the starting value for the loop. The
TO attribute refers to the value at which
iteration should stop. STEP specifies the
increment value for each iteration of the loop.
STEP may be either a positive or a negative
number. Here is an example that uses an index loop to output all the
numbers between 10 and 100 in
increments of 10, with each number on its own
line:
<H2>Calling the loop...</H2>
<CFLOOP INDEX="i"
FROM="10"
TO="100"
STEP="10">
<CFOUTPUT>
#i#<BR>
</CFOUTPUT>
</CFLOOP>
<H2>We are now outside of the loop</H2>Here, INDEX is set to i. Since
we want to begin the count at 10, we assign that
value to the FROM attribute. The
TO attribute is set to 100 because ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access