ColdFusion: cfscript to determine if variable exists and output html-escaped

  • October 8, 2009
  • James Skemp
  • article

There may be an easier way to do this in ColdFusion, but I finally created a function to determine whether a variable exists and if it does, returns in, all html-escaped.

<cfscript>
    // Checks the passed CF variable to see if it exists, and if it does, outputs a trimmed and html-ready version of the value.
    function checkForValueOutput(data) {
        if (IsDefined(data)) {
            return HtmlEditFormat(Trim(Evaluate(data)));
        } else {
            return "";
        }
    }
</cfscript>

(Obviously, this can rather easily be converted to a function.)

This results in a change from:

<input type="text" id="someField" name="someField" value="<cfif IsDefined("FORM.someField") AND Trim(FORM.someField) NEQ ""><cfoutput>#HtmlEncodedFormat(Trim(FORM.someField))#</cfoutput></cfif>" />

To:

<input type="text" id="someField" name="someField" value="<cfoutput>#checkForValueOutput("FORM.someField")#</cfoutput>" />

Much easier to read, and much shorter.