BackUp LevelNext

About Dynamic Expression Evaluation

Dynamic expression evaluation is an advanced technique in ColdFusion application development that allows CFML expressions to be created dynamically using string operations and evaluated as needed. Expressions are evaluated using one or more of the four dynamic expression evaluation functions -- Evaluate, SetVariable, IIf, and DE.

To appreciate the power and flexibility of dynamic expressions in CFML, you must first understand what dynamic expressions are and how are they used.

String expressions

Central to the notion of dynamic expression evaluation is the concept of a string expression. A string expression is nothing more than a CFML expression inside a string, for example, "1+1".

Any CFML expression can be converted to a string expression by following these simple steps:

The following table shows several examples of the process:

Sample Conversions to String Expressions 
Step 1
Step 2
Step 3
2
2
"2"
2 * (11 MOD 3)
2 * (11 MOD 3)
"2 * (11 MOD 3)"
Form.MyFormVariable
Form.MyFormVariable
"Form.MyFormVariable"
Min(X, Y)
Min(X, Y)
"Min(X, Y)"
"Some text"
""Some text""
"""Some text"""
"A double quote """
""A double quote """"""
"""A double quote """""""

The last two examples demonstrate one of the difficulties with string expressions -- the proliferation of quotes. In general, if some expression text has N double quote characters in it, its string expression equivalent will have 2*N+2 double quotes in it (every double quote must be escaped and two more are added one on either end of the expression text). In the last example, the expression text has 4 double quotes to start with, therefore its string expression equivalent has 10!

This explosion of double quotes makes string expressions harder to read. There are two things you can do to improve the situation. The simplest thing to do is to mix single and double quotes. The last two examples from above then could take the following form:

Simplifying String Expressions 
Step 1
Step 2
Step 3
'Some text'
'Some text'
"'Some text'"
"Some text"
"Some text"
'"Some text"'
'A double quote "'
'A double quote ""'
"'A double quote ""'"

You can also use the DE (Delay Evaluation) function to convert strings to string expressions. It has a specific use within dynamic expression evaluation, but it comes in handy for this particular task. Start by storing the text of the expression you want to convert to a string expression in a variable. Then apply the DE function to that variable to get the desired result.

For example, the following two pieces of CFML code are equivalent:

<CFSET TheStringExpression = "'A double quote ""'">

<CFSET TheExpression = 'A double quote "'>
<CFSET TheStringExpression = DE(TheExpression)>

See the CFML Language Reference for details on the DE function.


BackUp LevelNext

allaire

AllaireDoc@allaire.com
Copyright © 1998, Allaire Corporation. All rights reserved.