Not yet rated

Problem

A common web development issue is how to write reusable code that can then be inserted wherever needed. Most server-side languages provide some facility for this, and ColdFusion can as well.

Solution

With ColdFusion, you have several different options when you want to write reusable code. Probably the most used, and most familiar, is writing an "include" file: a small .cfm template of some bit of HTML output that can be inserted whenever necessary, and as often as needed. There are two methods for including a file in process.

Detailed explanation

Server-side processing languages move us a step beyond basic HTML, allowing one to write some bit of process or display that can be reused over and over again, even within the same page request. ColdFusion provides multiple ways of going about this, and each implementation has it's own uses. One of the earliest, most prolific, and simplest implementations is the use of a server-side "include". Basically, the ability for us to include one template within the process of another.

Let's look at a basic scenario. We have created two templates that we want to include in every display page of our site: header.cfm and footer.cfm. These two pages are just what they sound like, the header and footer of every page, most likely containing the site's navigation layout, copyright, etc. We can include a template using one of two methods: tag or script.

ColdFusion's tag syntax works much like HTML. To include our "header" template, we would use the cfinclude tag:

<!--- Include the "header" template --->
<cfinclude template="header.cfm" />

Some developers prefer to 'script' their processes. For this reason, ColdFusion 9 now introduces the ability to script your template inclusions:

<cfscript>
     // Include the "header" template
    include "header.cfm";
</cfscript>

That's it! It can't get much easier than that! Used properly this is very powerful. For instance, say you were outputting a table of information based on a query. You might have a template that represents a row of that table. You might include a "tablerow.cfm" to handle the processing of the display of those rows:

<cfloop query="REQUEST.ourQuery">
    <cfinclude template="tablerow.cfm" />
</cfloop>

Variables set to the Url, Form, Request, or Variables scopes, within an included template, are available to all templates processing after that template, as well as the onRequestEnd() method of our Application.cfc.

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes