Switch (true) with dynamic cases in coldfusion?

To avoid nested if statements and improve readability, I wanted to create switch(true){ ... } in Coldfusion. I often used this in php, but when I try this in Coldfusion, I get the following error on initialization:

Template Error

This expression must have a constant meaning.

This happens when a variable in its state is used in the case of a switch, for example:

 //this example throws the error switch(true){ case foo == 1: writeOutput('foo is 1'); break; } 

Using the switch (true) {...} operator with constant values ​​(as the error explains) works:

 //this example doesn't throw the error switch(true){ case 1 == 1: writeOutput('1 is 1'); break; } 

Is there a way to get the first statement to work in Coldfusion? Maybe with evaluating a variable or some tricks, or is it definitely not going to Coldfusion?

+6
source share
2 answers

In short: no. The case value must be something that can be compiled with a constant value. 1==1 can be as simple as true . foo == 1 cannot be, since foo is only available at run time.

basically what you are describing is an if / else if / else , so just use one of them.

+2
source

As Adam and Lee pointed out, the meaning of the case must be 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#"); } 
+2
source

All Articles