The IIf function is a shorthand for the following code:
<cfif argument1> <cfset result = Evaluate(argument1)> <cfelse> <cfset result = Evaluate(argument2)> </cfif>
The function returns the value of the result variable. It is comparable to the use of the JavaScript and Java ? : operator, and can result in more compact code. As a result, the IIF function can be convenient even if you are not using dynamic expressions.
The IIF function requires the DE function to prevent ColdFusion from evaluating literal strings, as the following example shows:
<cfoutput> #IIf(IsDefined("LocalVar"), "LocalVar", DE("The variable is not defined."))# </cfoutput>
If you do not enclose the string "The variable is not defined." in a DE function, the IIF function tries to evaluate the contents of the string as an expression and generates an error (in this case, an invalid parser construct error).
The IIF function is useful for incorporating ColdFusion logic in-line in HTML code, but it entails a processing time penalty in cases where you do not otherwise need dynamic expression evaluation.
The following example shows using IIF to alternate table row background color between white and gray. It also shows the use of the DE function to prevent ColdFusion from evaluating the color strings.
<cfoutput> <table border="1" cellpadding="3"> <cfloop index="i" from="1" to="10"> <tr bgcolor="#IIF( i mod 2 eq 0, DE("white"), DE("gray") )#"> <td> hello #i# </td> </tr> </cfloop> </table> </cfoutput>
This code is more compact than the following example, which does not use IIF or DE:
<cfoutput> <table border="1" cellpadding="3"> <cfloop index="i" from="1" to="10"> <cfif i mod 2 EQ 0> <cfset Color = "white"> <cfelse> <cfset Color = "gray"> </cfif> <tr bgcolor="#color#"> <td> hello #i# </td> </tr> </cfloop> </table> </cfoutput>