This blog is now obsolete. Go to scott.arbeitman.id.au for all new content.

0

Building a Better CFLOOP

| Saturday, June 23, 2007
ColdFusion 8 introduces slightly improved looping for arrays, as well a new way to loop over the contents of the file. Unfortunately, I don't believe these changes go far enough and, as I'll demonstrate, even better results can be accomplished even with older versions of ColdFusion.

My improved looping tag uses a little known ColdFusion feature, the <cfexit method="loop" /> tag. When used inside a custom tag, this returns control to the top the tag's "end" execution mode. This is ColdFusion's way of allowing custom iterators.

Here's what the syntax of my array looping tag:


<cfimport taglib="/custom-tags/loop/" prefix="loop" />

<loop:array array="#myArray#" index="i" element="e" cycle:shading="light,dark" cycle:odd="true,false" cleanup="true">

</loop:array>


Let me break it down:

  • array: this is the array you want to loop through, just like a regular CFLOOP

  • index: again, just like in CFLOOP, except this attribute is not required and has no defaults. it simply is not set.

  • element: the current item in the array. By default this a variable called element

  • cycle:variableName: the tag sets variableName to one of the values based on current index. This is inspired by a similar function in Rails. For example, in the above example, the variable odd will either have the value of true or false depending on the iteration number.

  • cleanup: This is perhaps the nicest feature. cleanup will remove references to all variables created during the iteration of the tag. This eliminates the need to var-scope lots of variables inside a CFC. By default, this is true.

Update
I've posted the code on github.