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.