Simon Baynes: Web Development

cfscript insight! Part (1)

A massively underused part of the ColdFusion language is cfscript. This is mainly because as a language that primarily uses tags to achieve all of its functions, starting to write script seems a bit alien. Obviously those of you who start using ColdFusion with a programming background will take to scripting straight away, but those who move into CF from a web design perspective will be a little more resistant.

Now before I show you a few things that you can use cfscript for, I must stress that there is nothing that you NEED cfscript for it is just an alternative that can have some minor performance bonuses.

Basics
You can only use cfscript statements between an opening and closing cfscript tag.
You cannot use any cf tags inside a cfscript block.
All cfscript commands must end in a semi-colon(;).

Setting Variables
Usually variables are set using cfset, in cfscript you can just write the name value pairs without the command:-

<cfscript>
    fName = "Simon";
    lName = "Baynes";  
</cfscript>

is the same as

<cfset fName = "Simon">
<cfset lName = "Baynes">

While they are identical in their end product, setting a variable within a cfscript block is actually performed quicker by the CF Application Server.

If Statements
Anyone who has done any ActionScripting in Flash will recognise how if statements are handles.

<cfscript>
    if (NOT IsDefined("URL.PageNum")) {  
        PageNum = 1;
    }
    else {
        PageNum = URL.PageNum;
    }
</cfscript>

is the same as

<cfif NOT IsDefined("URL.PageNum")>
    <cfset PageNum = 1>
<cfelse>
    <cfset PageNum = URL.PageNum>
</cfif>

There is no equivalent of cfelseif, but you can replicate its functionality in the following manner.

<cfscript>
    CurrentMonth = DateFormat(Now(), "m");  

    if ((CurrentMonth LTE 3) OR (CurrentMonth GTE 11)) {
        CurrentSeason = "Winter";  
    }
    else if (CurrentMonth LT 6) {
        CurrentSeason = "Spring";
    }
    else if (CurrentMonth LTE 8) {
        CurrentSeason = "Summer";
    }
    else {
        CurrentSeason = Autumn;
    }
</cfscript>

I will go further into the uses of cfscript in later issues, but hopefully this will wet your appetite for the moment.

By Simon Baynes