Writing Output

You can’t directly output text or variable values to the browser within a cfscript block. There is, however a function called WriteOutput( ) that you can use to write directly to the page output stream. This technique can output both variable values and plain text from within a cfscript block. Example 19-1 demonstrates the WriteOutput( ) function.

Example 19-1. Using the WriteOutput( ) function within a cfscript block

<h2>Using WriteOutput Within cfscript</h2>
   
<cfscript>
 x = 1;
 y = 2;
 MyMessage = "Hello World";
 
 WriteOutput("x = #x# <br>");
 WriteOutput("MyMessage = #MyMessage# <br>");
 WriteOutput(x+y); 
</cfscript>

In this case, because there is no way to embed HTML directly within the cfscript block, all formatting is done by embedding the HTML code within the WriteOutput( ) function. Executing Example 19-1 results in the output shown in Figure 19-1.

Using WriteOutput( ) within a CFScript block to write to the page output stream

Figure 19-1. Using WriteOutput( ) within a CFScript block to write to the page output stream

It is also possible to output the value of variables set within a cfscript block outside of the cfscript tags. This is accomplished by using a cfoutput block outside the cfscript block to handle the actual output, as shown in Example 19-2.

Example 19-2. Outputting CFScript variables outside the cfscript block

<h2>Using cfoutput To Output Variables Created Within cfscript</h2> <cfscript> x = 1; y = 2; MyMessage = "Hello World"; </cfscript> ...

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.