loops - Knowing when to insert a comma in ColdFusion -
every often, either in display code or in assembling string, i'll making list , need figure out how insert commas in list.
this how it:
<cfset hide_comma=true> <cfloop ... kind of loop ...> <cfif hide_comma><cfset hide_comma=false><cfelse>,</cfif> .... rest of code here ... </cfloop>
i'm wondering if there's cleaner way of doing this. realize 1 option following:
<cfset output_as_array = []> <cfloop ... kind of loop ...> <cfset loop_output = ""> ... rest of code here, append output loop output instead ... <cfset arrayappend(output_as_array, trim(loop_output))> </cfloop> <cfoutput>#arraytolist(output_as_array, ", ")#</cfoutput>
but doesn't seem clearer.
in django, in contrast, each loop has built in counter can write like:
{% ... kind of loop ... %} {% if not forloop.first %},{% endif %} ... rest of code here ... {% endfor %}
pretty same logic, there's built-in way check loop state, rather having create 1 on own. know when looping through <cfoutput query=...>
can use queryname.rowcount
purpose, can't find similar in documentation cfloop
s.
for compiling variable, using valuelist (for queries) , arraytolist functions sensible approach.
if not dealing query or array, build array using arrayappend convert string arraytolist.
(note: listappend ok 1 or 2 items, in long loop it's slower using arrayappend+arraytolist - see info here.)
regarding:
pretty same logic, there's built-in way check loop state, rather having create 1 on own. know when looping through can use queryname.rowcount purpose, can't find similar in documentation cfloops.
short answer: no, there isn't built-in automatic index loops in coldfusion, other standard from/to , query loops.
index loops, can of course use index:
<cfloop index="index" from=1 to=#arraylen(myarray)#> <cfif index gt 1> not first row </cfif> </cfloop>
for query loops, use rowcount:
<cfloop query="myquery"> <cfif myquery.rowcount gt 1> not first row </cfif> </cfloop>
for looping through items, need create own variable:
<cfset row = 0 /> <cfloop index="item" array=#myarray#> <cfif ++row gt 1> not first row </cfif> </cfloop> <cfset row= 0 /> <cfloop item="item" collection=#mystruct# > <cfif ++row gt 1> not first row </cfif> </cfloop>
in railo, can specify both index , item attributes , have both values available:
<cfloop index="index" item="item" array=#myarray#> <cfif index gt 1> not first row </cfif> </cfloop>
the index refers key though, cannot structs (you'll key name, not row number).
Comments
Post a Comment