Jump Start To ColdFusion MX - Looping In ColdFusion
(Page 4 of 6 )
The next topic that I am going to cover is looping in ColdFusion. To loop through just about anything in ColdFusion, you would use the <cfloop> tag. With this tag you can loop through a query, a list, an array, a structure, do for loops, and conditional loops. I am going to cover just the basics here. To loop through a query use the query attribute of <cfloop> like this:
<cfloop query="myQuery">
HTML and CF code here
</cfloop> Its that simple. Now, let's go through how to loop from one number to another and output that number:
<cfloop from="1" to="100" index="number">
<cfoutput>#number#</cfoutput><br>
</cfloop> This is similar to a for loop that you would use in PHP or ASP. The index attribute is used in other pieces of code like output, or an if statement. Here’s how to loop through a list:
<cfset myList="1,2,3,4,5,6,7,8,9">
<cfloop list="#myList#" index="listItem">
<cfoutput>#listItem#</cfoutput>
</cfloop> There is an optional attribute – delimiter -- that allows you to specify the delimiter for a given list. The default delimiter is a comma. Now, to loop over a structure you would use the collection and item attributes like this:
<cfset products = StructNew()>
<cfset val = StructInsert(products, "Appliances ", "Dryer ")>
<cfset val = StructInsert(products, "Furniture ", "Couch")>
<cfset val = StructInsert(products, "Electronics ", "Tv ")>
<cfloop collection="#products#" item="cartitem">
#products#<br>
#StructFind(products, cartitem)#<br><br>
</cfloop> I know that I have not covered everything about loops, but this gives you the basics to start using them. In a more advanced article I delve into loops in greater detail.
Next: Form Handling >>
More ColdFusion Articles
More By Clint Tredway