To avoid nested if-statements and to improve readability, I wanted to create a
switch(true){ ... }
statement in Coldfusion. I used this often in php, but when I try this in Coldfusion, I get the following error at initialization:
Template error
This expression must have a constant value.
This happens when a switch case uses a variable in its condition, like:
//this example throws the error
switch(true){
case foo == 1:
writeOutput('foo is 1');
break;
}
Using a switch(true){ ... } statement with constant values (as the error explains) does work:
//this example doesn't throw the error
switch(true){
case 1 == 1:
writeOutput('1 is 1');
break;
}
Is there any way to get the first statement to work in Coldfusion? Maybe with an evaluation of the variable or some trick, or is this a definite no go in Coldfusion?
In short: no. The case value needs to be something that can be compiled to a constant value. 1==1
can be, as it's just true
. foo == 1
cannot be, as foo
is only available at runtime.
basically what you're describing is an if
/ else if
/ else
construct anyhow, so just use one of those.
As Adam and Leigh pointed out, the case values need to be some constant. I'm not sure what your actual use case is but you can do something like this:
switch(foo){
case 1:
writeOutput('foo is 1');
break;
case 2:
writeOutput('foo is 2');
break;
case 3:
writeOutput('foo is 3');
break;
case 4:
case 5:
case 6:
writeOutput('foo is 4 or 5 or 6');
break;
default:
writeOutput("I do not have a case to handle this value: #foo#");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With