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> <cfoutput> <cfloop index="i" from="10" to="100" step="10"> #i#<br> </cfloop> </cfoutput> <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 that is where ...
Get Programming ColdFusion MX, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.