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!)

Tags: ,

Monday, November 11th, 2013 ColdFusion

2 Comments to Converting lines to a list in ColdFusion

  1. Ben Nadel also points out that cfloop handles files this way when using the file attribute. See Reading in file data one line at a time for an example.

  2. Chris Herdt on November 13th, 2013
  3. 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.)

  4. Chris Herdt on August 13th, 2014

Leave a comment