One of the greatest things about ColdFusion is that it can dynamically create screen content for your pages from variables. These variables can be the simple data types that we created in the last section or can be complex data types that we'll cover soon. The next thing that we need to cover is how to write these variables' values to the browser. Outputting ValuesColdFusion uses a tag called CFOUTPUT to enable ColdFusion variables to be written to the browser. The CFOUTPUT tag requires both an open tag and a close tag: <cfoutput> Your code goes here. </cfoutput> There really is nothing dynamic about the preceding code. Let's add a little more code, and we'll really start to see ColdFusion at work. Listing 4.3 Writing Data to a Page with a Simple CFOUTPUT<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>More Examples</title> </head> <body> <cfset variables.myname="Neil"> <cfset variables.booksite="http://www.insidecoldfusionmx.com"> <cfset variables.email="neil@insidecoldfusionmx.com"> <cfoutput> Hello, my name is #variables.myname#. <br> <br> If you want to check out more examples visit #variables.booksite#, or email me at #variables.email# </cfoutput> </body> </html> You'll notice in Listing 4.3 that when we output the value of a variable, we must surround our variable name with pound signs (#). This is required because ColdFusion uses the pound signs to identify which parts of the page are variables and which are literal strings. ColdFusion attempts to evaluate any expression surrounded by pound signs. HTML uses pound signs in conjunction with hexadecimal colors. Any time that they occur within a CFOUTPUT tag as HTML, the pound signs must be escaped or ColdFusion attempts to evaluate the expression, resulting in an error. To escape the pound sign, just add an additional pound sign in front of it. Check out Listing 4.4. Listing 4.4 Escaping the Pound Sign<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <cfset variables.myname="Neil"> <cfset variables.booksite="http://www.insidecoldfusionmx.com"> <cfset variables.email="neil@insidecoldfusionmx.com"> <cfoutput> <table bgcolor="##EDD18F"> <tr> <td> Hello, my name is #variables.myname#. <br><br> If you want to check out more examples visit #variables.booksite#, or email me at #variables.email# </td> </tr> </table> </cfoutput> </body> </html> Notice that the bgcolor attribute of the table has an extra pound sign before the hexadecimal color. This is where we've escaped the original pound sign. LoopingThere are times when we need to output variables that contain more than a single value. Looping is a technique that we use in ColdFusion to output query results, lists, and other groups of values as you might have with arrays, structures, and query objects. Looping is a very powerful programming tool because it enables us you to loop through an entire set of instructions, repeating the output and any code that is contained within the loop. A simple loop might look something like this: <cfloop looptype="expression"> HTML and CFML code here ... </cfloop> Note Let us point out here that there is no attribute within the CFLOOP tag called "LOOPTYPE"; this reference is merely to convey that the structure of the CFLOOP tag itself is the same regardless of the type of loop that you use. The differences are in the syntax of the required and optional attributes for each type of loop. Loops can be nested, which is useful for grouping data. Nested loops must be properly formed with a closing CFLOOP tag for each nested loop. The code within the nested loop processes in its entirety with each iteration of the outer loop. Nested loops look something like this: <cfloop looptype="expression"> HTML and CFML code here ... <cfloop looptype="expression"> HTML and CFML code here ... </cfloop> More HTML and CFML code here ... </cfloop> There are two ways to loop through values in ColdFusion. You can use the CFLOOP tag or you can add the query attribute to the CFOUTPUT tag. Probably the most commonly used of these two methods would be the CFOUTPUT tag, but let's look at the CFLOOP tag first because it is just as important to know how to implement a good CFLOOP. Looping with CFLOOPThe CFLOOP tag is commonly used for looping through the output of lists, queries, or collections. To output values to the browser using CFLOOP, you must also use the CFOUTPUT tag within the loop. There are five types of loops:
Index LoopAn Index loop runs a number of iterations based on a value range set by its from and to attributes. Index loops are similar to for loops in other programming languages. An Index loop is a loop that executes the same set of code for as many times as the range between the values specified in the FROM and to attributes of the CFLOOP tag. There are three required attributes in an Index loop:
Consider the following example of an Index loop. Listing 4.5 Index Loop<cfoutput> <cfloop index="i" from="1" to="5"> Current loop index value = #i# </cfloop> </cfoutput> When we run Listing 4.5, we get a simple output of the index values, as shown in Figure 4.1. Figure 4.1. Result of using an index loop.
Conditional LoopA Conditional loop is a loop that continues to run and execute all code within the loop until the specified condition is evaluated as FALSE. For that reason, each loop should change the value that the condition evaluates. When the condition is no longer TRUE, the loop ends and the remainder of the template is executed. The conditional loop is also known as the While loop. See Listing 4.6. Listing 4.6 Conditional Loop<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Conditional Loop</title> </head> <body> <cfset variables.loopcount=1> <cfloop condition="variables.loopcount LESS THAN OR EQUAL TO 5"> Current condition loopcount value = <cfoutput>#variables.loopcount#</cfoutput> <br><br> <cfset variables.loopcount= variables.loopcount+1> </cfloop> </body> </html> Listing 4.6 is a bit different from our last example in Listing 4.5, but it renders very similar results on the screen (see Figure 4.2). Figure 4.2. Conditional loop output.
Query LoopThe Query loop can be used if you have a ColdFusion query object through which to loop. A Query loop iterates for every record returned in the query result set. In this case, the CFLOOP output is the same as the CFOUTPUT with the query attribute. The Query loop enables you to loop over tags, just as with CFOUTPUT, that might not be nested within a CFOUTPUT except where you use the QUERY and group attributes within the outer CFOUTPUT tag. Listing 4.7 Query Loop<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <!--- Get User Records ---> <cfquery name="getUsers" datasource="ICFMX"> SELECT * FROM Users </cfquery> <!--- Get User Records ---> <cfoutput> <cfloop query="getUsers"> #getUsers.UserFirstName# #getUsers.UserLastName# - #getUsers.UserEmail#<br> </cfloop> </cfoutput> </body> </html> The Query loop continues to execute for each record returned by the query and to execute all code within the loop as well. Notice that in Listing 4.7 I've properly scoped my output variables back to the getUsers query. List LoopWe said earlier that a list is merely a string of values that are separated by some delimiter. Each value in the list is called an element. A List loop iterates through each element in a list until it evaluates each value. The List loop must have a list defined in the list attribute, by either naming a ColdFusion variable or providing a literal string. You must also specify the index attribute, which is a variable that signifies the position of each item in the list. The value of the index is the value of the current element of the list. See Listing 4.8. Listing 4.8 List Loop<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <!--- Define my table list ---> <cfset variables.tables="categories,customers,products"> <!--- Output my table list ---> My list contains: <cfloop list="#variables.tables#" index="index_var"> <br><br> <cfoutput>#index_var#</cfoutput> </cfloop> </body> </html> Collection LoopA Collection loop enables you to iterate through values that are held in a ColdFusion structure or in a COM or Distributed Component Object Model (DCOM) collection object. In Listing 4.9, we loop through a simple structure to output the value of the current key. Listing 4.9 Looping Through a ColdFusion Structure<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <!--- Create a structure and loop through its contents ---> <cfset Authors = StructNew()> <cfset tmp = StructInsert(Authors, "FirstName", "Neil")> <cfset tmp = StructInsert(Authors, "LastName", "Ross")> <cfset tmp = StructInsert(Authors, "Email", "neil@codesweeper.com")> <!--- Output the Author Data ---> <cfoutput> <cfloop collection="#Authors#" item="AuthoInfo"> #AuthoInfo#<br> #StructFind(Authors, AuthoInfo)# <br> <br> </cfloop> </cfoutput> </body> </html> Ending a LoopAt any point within your loop, it is easy to break the loop and continue with the processing of the remainder of the page. Place a CFBREAK tag within the loop and as soon as it is reached, the loop ends and the template code continues to process with the first line immediately following the closing CFLOOP tag. Example 4.10 Listing 4.10 Index Loop<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <cfset variables.lastloop=5> <cfloop index="i" from=1 to=#variables.lastloop#> <cfif variables.lastloop IS 3><cfbreak></cfif> Current loop index value = <cfoutput>#i#</cfoutput> <br><br> <cfset variables.lastloop=variables.lastloop-1> </cfloop> </body> </html> The code continues to process and write the values to the browser until it outputs the following: Current loop index value = 1 Current loop index value = 2 Looping with CFOUTPUTLooping with CFOUTPUT is probably the most commonly used looping method. It is used in conjunction with the ColdFusion query object. We've seen how to use the CFOUTPUT tag to output simple variables. To enable looping with the CFOUTPUT tag, we must add the query attribute and specify an available query. See Listing 4.11. Listing 4.11 Outputting Multiple Records with CFOUTPUT<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <!--- Get User Records ---> <cfquery name="getUsers" datasource="ICFMX_data"> SELECT * FROM User </cfquery> <!--- Output Selected User Records ---> <cfoutput query="getUsers"> #getUsers.UserFirstName# #getUsers.UserLastName# - #getUsers.UserEmail#,br> </cfoutput> </body> </html> By adding the query attribute to the CFOUTPUT tag, we've succeeded in doing exactly what the CFLOOP/CFOUTPUT combination would do, but with less code to write or maintain. Conditional Processing LogicConditional processing logic is the decision-making process within a ColdFusion template. Conditional logic is used to evaluate and compare expressions then process code based on the results of that comparison. ColdFusion gives us three methods of making runtime decisions within our code:
IF StatementsColdFusion uses a typical If/Else, style processing with the CFIF tag. The CFIF tag can be used to evaluate any statement that can return a Boolean value. The CFIF statement requires a closing CFIF tag. CFIF statements can include CFIF, CFELSEIF, and CFELSE tags, as well as other nested CFIF statements. <cfif 1+1 IS 3> HTML and CFML code here ... </cfif> The CFELSEIF tag is used within a CFIF statement and offers an option if the CFIF value is determined to be FALSE. There can be any number of CFELSEIF statements within a single CFIF statement. <cfif 1+1 IS 3> HTML and CFML code here ... <cfelseif 1*1 IS 2> HTML and CFML code here ... </cfif> The CFELSE tag provides the statement a default option. After the CFIF and all CFELSEIF tags have been evaluated to FALSE, the CFELSE tag process any code between it and the closing CFIF tag. <cfif 1+1 IS 3> HTML and CFML code here ... <cfelseif 1*1 IS 2> HTML and CFML code here ... <cfelse> execute this HTML and CFML code </cfif> Let's take a look at an IF statement that provides us with a better example of a CFIF statement. Listing 4.12 Example of CFIF Use<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <!--- Form Action Page ---> <cfif IsDefined("form.submit_button") AND form.submit_button IS "Update User"> <!--- Update the User ---> <cfquery datasource="ICFMX"> UPDATE Users SET UserName = '#form.UserName#', EAddress = '#form.EAddress#' WHERE UserID = #form.UserID# </cfquery> You've successfully updated the user information. <cfelseif IsDefined("form.submit_button") AND form.submit_button IS "Delete User"> <!--- Delete the User ---> <cfquery datasource="ICFMX"> DELETE FROM Users WHERE UserID = #form.UserID# </cfquery> You've successfully deleted the user information. <cfelse> You've entered this page improperly. Please press the back button on your browser. </cfif> </body> </html> The following rules apply to CFIF statements:
SWITCH StatementsThe biggest advantages of the CFSWITCH/CFCASE/CFDEFAULTCASE statements are the ease of readability and the increase in performance. The CFSWITCH/ CFCASE/CFDEFAULTCASE statement should take the place of a CFIF statement with multiple CFELSEIF statements. A typical CFSWITCH/CFCASE/CFDEFAULTCASE statement looks something like Listing 4.13. Listing 4.13 Typical CFSWITCH/CFCASE/CFDEFAULTCASE Statement<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ColdFusion Template Syntax</title> </head> <body> <cfswitch expression="#url.product_id#"> <cfcase value="1"> <cfinclude template="/products/product1.cfm"> </cfcase> <cfcase value="2"> <cfinclude template="/products/product2.cfm"> </cfcase> <cfcase value="3"> <cfinclude template="/products/product3.cfm"> </cfcase> <cfcase value="4"> <cfinclude template="/products/product4.cfm"> </cfcase> <cfcase value="5"> <cfinclude template="/products/product5.cfm"> </cfcase> <cfdefaultcase> <cfinclude template="/products/index.cfm"> </cfdefaultcase> </cfswitch> </body> </html> I know there's a much easier way to write the statement. Send an email to info@insidecoldfusionmx.com if you're not sure how to streamline it and type Listing 4.13 in the subject line. IIf Inline Conditional ProcessingThe IIf() function is used as an inline IF statement. The IIf() function is primarily used to evaluate dynamic expressions and to return a Boolean value inline. You've probably seen the IIf() function used in ColdFusion training classes to create rows with alternating background colors. The IIf() function is good for much more than setting background colors, however. It is probably a very underused ColdFusion function, primarily because developers just don't understand it. Have you ever wanted to vary your code according to the time of day? Check out the code in Listing 4.14 using the IIf() function. Listing 4.14 Using the IIf() Function to Load Dynamic Content<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>IIf Dynamic Content</title> </head> <body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0"> <table width="800" cellspacing="0" cellpadding="0"> <tr> <td><cfoutput><img src="/books/2/197/1/html/2//display_code/images/#IIf( Hour(Now()) GT 12, DE("evening"), DE("morning"))#.gif"></cfoutput></td> <td width="10"></td> <td valign="top"><cfinclude template="/display_code/#IIf( Hour(Now()) GT 12, DE( "evening"), DE("morning"))#.cfm"></td> </tr> </table> </body> </html> Based on whether it is before or after noon, we load an appropriate image to take up the left side of the screen and include varying content on the right. The screen would look something like Figure 4.3. Figure 4.3. Evening content.
SummaryDisplaying variable values in the browser is an easy-to-master process. A simple CFOUTPUT handles many jobs; for data types that are more complex, try looping with CFLOOP or the CFOUTPUT tag and specify the query. Up to this point, we've learned how to set variables and write them to the screen. However, what if our variable values are sitting in a database somewhere? In the next section, we see how getting data from a database is a useful skill to have. |