Flow Control and Looping
CFScript contains a number of
statements to handle flow control and looping, as
we’ll discuss in this section. Note that you
can’t use any CFML tags within a
cfscript
block.
if/else
The
if/else
statement has the same functionality as
the cfif
and cfelse
(and by
extension, cfelseif
) tags in regular CFML. The
if
statement can be used alone, as in:
if (expression
)statement
;
Or it can be used with the else
statement, as in:
if(expression
)statement
; elsestatement
;
You can also use the else
and
if
statements in combination to achieve the same
results as the cfelseif
tag:
if (expression
)statement
; else if (expression
) statement; elsestatement
;
To understand the differences between the
cfif/cfelse
tags and the ifelse
statement, let’s first consider an example that uses
the cfif
and cfelse
tags. Example 19-3 assigns the current year to a variable called
TheYear
. The cfif
and
cfelse
tags are then used to determine whether the
current year is a leap year. The results are then written to the
browser.
Example 19-3. Determining if the current year is a leap year using cfif/cfelse
<!--- Set a variable equal to the current year ---> <cfset TheYear=Year(Now( ))> <!--- Check to see if the current year is a leap year. ---> <cfif IsLeapYear(TheYear)> <cfset ReturnOutput="is a leap year."> <cfelse> <cfset ReturnOutput="is not a leap year."> </cfif> <cfoutput> #TheYear# #ReturnOutput# </cfoutput>
The same code can easily be rewritten using CFScript. Example 19-4 shows the ported ...
Get Programming ColdFusion MX, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.