Converting lines to a list in ColdFusion

I’m so used to dealing with comma-delimited lists in ColdFusion that I would sometimes take a data file that had one item per line and replace the newline characters with commas.

It’s easy to use the carriage return [chr(13)] and line feed [chr(10)] characters as list delimiters, though, and remove the intermediary step. Here’s a quick example:

<cfsavecontent variable="data">
this
is
a
list
with
one
word
per
line
</cfsavecontent>

<cfoutput>
    <ol>
        <cfloop list="#data#" delimiters="#chr(13)##chr(10)#" index="line">
            <li>#line#</li>
        </cfloop>
    </ol>
</cfoutput>

Which produces the following:

  1. this
  2. is
  3. a
  4. list
  5. with
  6. one
  7. word
  8. per
  9. line

(I can’t believe I didn’t think of this until today!)

3 thoughts on “Converting lines to a list in ColdFusion”

  1. You can also use this technique in a cfqueryparam tag when the list attribute is set to true:

    <cfqueryparam value=”#myValue#” list=”yes” separator=”,#chr(13)##chr(10)#”></code>

    In this case, I included both a comma and CRLF, so that it can handle lists of either type (or even a mixed type).

    (It’s unfortunate that the attribute is delimiter in most list-related tags, but separator in cfqueryparam.)

Leave a Reply

Your email address will not be published. Required fields are marked *