Every so often, either in display code or in assembling a string, I'll be making a list and need to figure out how to insert commas in that list.
This is how I usually do it:
<cfset hide_comma=true>
<cfloop ... some kind of loop ...>
<cfif hide_comma><cfset hide_comma=false><cfelse>,</cfif>
.... rest of code here ...
</cfloop>
I'm wondering if there's a cleaner way of doing this. I realize one option would be something like the following:
<cfset output_as_array = []>
<cfloop ... some kind of loop ...>
<cfset loop_output = "">
... rest of code here, but append all output to loop output instead ...
<cfset ArrayAppend(output_as_array, trim(loop_output))>
</cfloop>
<cfoutput>#ArrayToList(output_as_array, ", ")#</cfoutput>
But that doesn't really seem any clearer.
In Django, in contrast, each loop has a built in counter so I can write something like:
{% for ... some kind of loop ... %}
{% if not forloop.first %},{% endif %}
... rest of code here ...
{% endfor %}
Pretty much the same logic, only there's already a built-in way to check loop state, rather than having to create one on my own. I know that when looping through a <cfoutput query=...>
I can use QueryName.RowCount
for this purpose, but can't find anything similar in the documentation for CFLOOP
s.