the singularity of being and nothingness
ColdFusion Gotcha: Switch Statement in CFScript
The other day, I was reworking a bit of tag-based code to use my preference of <cfscript> syntax. While doing this, I ran across something like this:
<cfswitch expression="#img.extension#"> <cfcase value=".gif,.jpg"> Not transparent </cfcase> <cfcase value=".png"> Transparent </cfcase> </cfswitch>
No rocket-science here, just a simple switch statement which just so happens to have a “case” which evaluates a list of values. Honestly, I’m not sure I had ever done a list of values in a <case>, but it just works.
Thinking nothing of it, I quickly converted it to <cfscript> syntax:
<cfscript>
switch(img.extension) {
case ".gif,.jpg":
writeoutput("Not transparent");
break;
case ".png":
writeoutput("Transparent");
break;
}
</cfscript>
At first, I thought it was working. But as I tested a bit more, I noticed that it wasn’t. No error, per se, but the “case” was not evaluating as it did in the tag-based equivalent.
Turns out you have to do something a bit different with <cfscript>. Here’s an alternative that will replicate the tag-based functionality:
<cfscript>
switch(img.extension) {
case ".gif": case ".jpg":
writeoutput("Not transparent");
break;
case ".png":
writeoutput("Transparent");
break;
}
</cfscript>
According to the docs,
Multiple
caseconstant: statements can precede the statement or statements to execute if any of the cases are true. This lets you specify several matches for one code block.
Ah, so it’s a “feature.” Hmm, personally, I think this feels kind of clunky. I imagine there is a good reason for why it’s done this way, but I’d love to know why-anyone?
| Print article | This entry was posted by existdissolve on August 30, 2011 at 12:07 pm, and is filed under ColdFusion. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |


about 1 year ago
The way you’re used to with tags is actually the hacky/kludgy way.
The script way has been used by classical languages (C, Java, etc) since before CF was a gleam in Jeremy Allaire’s eye.
switch(foo){
case 1:
case 2:
case 3:
do1or2or3();
break;
case 4:
case 5:
case 6:
do4or5or6();
break;
}
… and so on. When They tried to recreate this in CFML tags, the equivalent was not intuitive at all!
- the tags aren’t balanced. So that’s why they introduced the comma syntax for tags. But it makes sense for cfscript to stay inline with the classical languages it resembles.
about 1 year ago
That makes sense-thanks for the explanation.