User Guide

Table Of Contents
36 Chapter 2: Elements of CFML
This section provides a basic introduction to using flow-control tags. CFScript also provides a set
of flow-control statements. For information on using flow-control statements in CFScript, see
Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” on page 123. For more details
on using flow-control tags, see the reference pages for these tags in CFML Reference.
cfif, cfelseif, and cfelse
The
cfif, cfelseif, and cfelse tags provide if-then-else conditional processing, as follows:
1.
The cfif tag tests a condition and executes its body if the condition is True.
2.
If the preceding cfif (or cfelseif) test condition is False, the cfelseif tag tests another
condition and executes its body if that condition is True.
3.
The cfelse tag can optionally follow a cfif tag and zero or more cfelseif tags. Its body
executes if all the preceding tags’ test conditions are False.
The following example shows the use of the
cfif, cfelseif, and cfelse tags. If the value of the
type variable is “Date,” the date displays; if the value is “Time,” the time displays; otherwise, both
the time and date display.
<cfif type IS "Date">
<cfoutput>#DateFormat(Now())#</cfoutput>
<cfelseif type IS "Time">
<cfoutput>#TimeFormat(Now())#</cfoutput>
<cfelse>
<cfoutput>#TimeFormat(Now())#, #DateFormat(Now())#</cfoutput>
</cfif>
cfswitch, cfcase, and cfdefaultcase
The
cfswitch, cfcase, and cfdefaultcase tags let you select among different code blocks
based on the value of an expression. ColdFusion processes these tags as follows:
1.
The cfswitch tag evaluates an expression. The cfswitch tag body contains one or more
cfcase tags and optionally includes cfdefaultcase tag.
2.
Each cfcase tag in the cfswitch tag body specifies a value or set of values. If a value matches
the value determined by the expression in the
cfswitch tag, ColdFusion runs the code in the
body of the
cfcase tag and then exits the cfswitch tag. If two cfcase tags have the same
condition, ColdFusion generates an error.
3.
If none of the cfcase tags match the value determined by the cfswitch tag, and the cfswitch
tag body includes a
cfdefaultcase tag, ColdFusion runs the code in the cfdefaultcase tag
body.
Note: Although the cfdefaultcase tag does not have to follow all cfcase tags, it is good programming
practice to put it at the end of the
cfswitch statement.
The cfswitch tag provides better performance than a cfif tag with multiple cfelseif tags, and
is easier to read. Switch processing is commonly used when different actions are required based on
a a string variable such as a month or request identifier.