YOUR FEEDBACK
E-Commerce 2.0
Brian wrote: I think we're heading in the right direction, but we've still...
SOA World Conference
Virtualization Conference
$200 Savings Expire May 16, 2008... – Register Today!


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP COLDFUSION LINKS


Paired Custom Tags

Digg This!

You may have heard that Release 4 of ColdFusion introduced support for nested and paired custom tags. This offers many possibilities for creating more complex custom tags.

In this month's Journeyman ColdFusion I'll introduce you to paired custom tags.

Paired custom tags are similar to simple custom tags except that instead of just a single tag, there's a closing tag as well. For instance, if there was a custom tag called "TEST", the simplest way to call it would be:

<CF_TEST>
or possibly:
<CF_TEST ATTR1="value1">

In the latter case, the TEST custom tag was obviously designed to accept a parameter, such as passing an ATTR1 attribute with a value of "value1".

(For those not familiar with custom tags, I recommend two of my previous articles that introduced the subject [CFDJ, Vol. 2, issues 4 and 5] at http://www.sys-con.com/coldfusion/article.cfm?id=102 and http://www.sys-con.com/coldfusion/article.cfm?id=112. I'll presume you're familiar with simple custom tags, how to create them, and how to pass parameters to them.)

Paired tags are a newer phenomenon, however, and many developers are slow to start using them. They're really not difficult to use or understand.

About Paired Custom Tags
The key difference with paired custom tags, of course, is that they're coded with both an opening and a closing tag, as in:

<CF_TEST>
</CF_TEST>

This may look strange at first, and in this case there may be no real reason to do it. But it becomes powerful when there's something specified between the tags, as in:

<CF_TEST>
This is a set of data that will be processed by the custom tag.
</CF_TEST>

The tag is still being provided with data to process, but instead of being provided as a parameter, it's being provided between the tags. You can still use parameters in paired tags:

<CF_TEST ATTR1="value1">
This is a set of data that will be processed by the custom tag.
</CF_TEST>

Paired tags provide you with more space and flexibility in specifying the data to be passed into the custom tag. This is one of the two main reasons to use them.

There's a lot to learn about using paired tags. It's not quite as simple as just using them in pairs; we'll discuss these subtleties later. However, we should realize that paired tags aren't really that foreign.

Paired Tags, Not Really New to Us
While the ability to use paired custom tags may be relatively new, we've certainly all dealt with paired tags before, both in HTML and in CFML. Consider the following:

  • <BODY></BODY>
  • <H2>/</H2>
  • <CFQUERY></CFQUERY>
  • <CFIF></CFIF>

These tags are designed to work in pairs only, that is, with a closing tag. You obviously can't do a <CFIF> without a closing </CFIF>. The same is true for the rest of the tags.

An important reason they're de-signed this way, though, is that each tag requires information, possibly quite a lot, to be passed to it to process.

For instance, an <H2> tag takes all the data between the tags and presents it in a larger, bolder font. A <CFQUERY> tag interprets all the data between the tags as SQL to be sent to a database. There may be a lot of information to be converted by the <H2> or interpreted by the <CFQUERY>, and trying to pass that as a parameter could become awkward.

Actually, at one time CF programmers did pass SQL as an attribute/value pair:

<DBQUERY NAME="HomeSearch" DATASOURCE="house1" SQL="SELECT * FROM Data WHERE ZIP = '#FORM.ZIP#'">

If you think about it, trying to pass in the SQL as a parameter has various limitations, not the least of which is that we wouldn't be able to embed other CF tags within the value of the "SQL" attribute, as in the example above.

While the designers of those HTML or CFML tags could accept that data as attributes (and we see that at one time with CFQUERY's ancestor DBQUERY they did), it made more sense to accept it as data between the tags.

It's just a simple design choice. The good news is that now designers of CFML custom tags have the same choice.

Using Paired Custom Tags
We've learned that one of the benefits of paired custom tags is that we can process the data between them. Now the question is: How do we use them? We need to understand a few of the characteristics of using paired custom tags, so follow along and we'll create some real code examples. We'll expand on them as we introduce new concepts.

First, create a program called call_test.cfm with the following lines:

<CF_TEST>
</CF_TEST>
This will call/execute a program called "test.cfm". If it had said <CF_TEST2>, it would try to call a program called test2.cfm. Note that the case is not sensitive, at least in Windows environments.

Let's create the test.cfm file and place it in the same directory as the call_test.cfm program. (Again, if you're new to custom tags in general, see my previous articles for information on alternative locations to place custom tag files.)

You may think you could just create an empty file since we're not doing anything yet in the custom tag; however, you'll get an error because a custom tag (and indeed any ColdFusion program) can't be empty. In test.cfm place the following code:

Inside the custom tag<br>
After saving both of them, when you run the call_test.cfm program you should see the following result:
Inside the custom tag
Inside the custom tag

What happened? The information inside the custom tag was presented twice? Welcome to an interesting facet of working with paired tags - they're executed twice! Once for the opening tag and again for the second tag. We'll deal with that later.

Adding Data Between the Paired Custom Tags
Right now we'll discuss what happens when we add some data between the custom tags. Let's add the words "between the pair" between the tags in call_test.cfm:

<CF_TEST>
Between the pair
</CF_TEST>

Running that, you should see this result:

Inside the custom tag
Between the pair Inside the custom tag
What's up with that? Well, it's consistent with the double execution of the tag. It may help to view the actual HTML that would result in that display:
Inside the custom tag<br>

Between the pair
Inside the custom tag<br>

We still see the "Inside the custom tag" line being generated by the double execution. But we also see the words "Between the pair" displayed between them. (We'll explain the blank line later.)

All this raises several questions:

  • How can we do something with the data that's passed between the pair? Right now, it's just being regurgitated.
  • What if we don't want the data displayed? What if we want to use the data for some purpose within the tag and not have it regurgitated at completion?
  • Exactly when is the data being displayed? Before, during, or after the first or second execution of the custom tag?
We'll address these in turn.

Accessing the Data Between the Tags
Remember that the reason for putting the data between the tags was so we could do something with it. How? Is it available as a variable?

In normal custom tags the data passed in as attribute/value pairs is available as a variable of the form, attributes.attributename, where at-tributename is the name of the attribute passed in (in our examples that showed passing of parameters, that would be attributes.attr1). We could then do whatever we like with that "attribute" variable, including printing it back to the user and using it within another ColdFusion tag.

In the case of paired custom tags, Allaire introduced an entirely new variable - and indeed a new prefix - to refer to the data between the tags. The new variable is:

thistag.generatedcontent
Notice the new prefix, "thistag" - it's a hard-coded, reserved word in ColdFusion now. It's literally the word, "thistag" (just as the other prefix was the word "attributes"). The variable name, "generatedcontent," is also a hard-coded, reserved word.

Like the "attributes" prefix, the "thistag" prefix is available only within a custom tag. The "generatedcontent" variable will have a value only when data is passed between paired custom tags.

As with any variable, we can print the variable or use it within another tag (perhaps a CFQUERY). Now add some code inside the test.cfm program to do something with the variable that holds that data. First we'll simply display it, also applying the ColdFusion string function Ucase() that will convert the data to uppercase. Add the following code to test.cfm, so we now have two lines in the program:

Inside the custom tag<br>
<cfoutput>#ucase(thistag.generatedcontent)#</cfoutput><br>
This will simply display the value of the data passed between the tags. The output of running call_test.cfm (if we viewed the HTML source) will be:
Inside the custom tag<br>
Between the pair
Inside the custom tag<br>

BETWEEN THE PAIR <br>

What's happening here? Well, the first two lines are created by the initial execution of the custom tag (from the "opening tag"). Remember, the code is executed twice. What we see from this, however, is that the "opening" execution of the custom tag has no value for the "thistag.generatedcontent" variable. It's empty. The variable does exist, but it's empty. That's why we just see a <br> with nothing in front of it. There was nothing to Ucase. What about the next two lines?

The Redisplay of the Data Between the Paired Tags
Where's the blank line and "Between the pair" coming from? It's the automatic display of the data between the tags that always takes place, which we saw earlier.

Notice that the data between the tags was simply displayed before the start of the second execution of the paired custom tag (in the closing tag). That's all that's happening here.

There's something a little trickier to take note of, though. In that earlier first example of running the paired tags, I didn't want to explain the blank line before the "Between the pair" text - it's simply a remnant of the fact that in the call_test.cfm program, we put the data between the paired tags on its own line.

What do I mean? The blank line we see in the HTML source just before "Between the pair" (which like all blank lines would be ignored when rendered in the browser) is due to a carriage return. Look really closely and you'll see that after the phrase "Between the pair", another carriage return is reflected because the next line ("inside the tag<br>") occurs on its own line.

If we had put the opening and closing tags and the data between them on one line, the blank line above the phrase and the carriage return after it would go away. It's not a critical point, but it's a characteristic that's not well documented and could lead to confusion if not understood.

The Second Execution: Where the Action Takes Place
The final four lines of output from that last example above remain unexplained:

Inside the custom tag<br>

BETWEEN THE PAIR
<br>

It should be obvious by now that the first line is the first line of the custom tag. We're merely executing it a second time as a result of the closing custom tag. The blank line and uppercased phrase "BETWEEN THE PAIR" and the carriage return that follows it (before the final <br>) are all the output of the processing of the Ucase() function in that second execution.

Clearly, that second execution is where the variable "thistag.generatedcontent" has a value. And again, its value is the text that was between the tags and the carriage returns before and after it, as explained above. They've all been uppercased. The output of all this would appear in the browser as:

Inside the custom tag

Between the pair Inside the custom tag
BETWEEN THE PAIR

Preventing the Automatic Redisplay of the Data
What if we want to clean this up a bit? What if we don't want to show the words "Inside the custom tag" (which we can just delete from the custom tag, as they were there as placeholders) or the data be-tween the pair (literally the words "Between the pair" above) to ap-pear automatically?

In our example, we just wanted to uppercase the data. We want it to function in a way that's similar to the <H2> tag. All that does is render the data in a larger font. The data only appears once, right? In our example there's no reason (in fact it's inappropriate) to have CF automatically display the data twice.

We saw earlier that the first display of the original mixed case data is an automatic display of the data between the tags, and it occurs before the start of the second execution of the tag (the closing tag).

It's a little more difficult than that. What's going on is that it's the value of the thistag.generatedcontent variable, as of the end of the second execution (the closing tag), that's being displayed. But it's displayed before any processing takes place in the closing tag.

This is hard to grasp at first but it's true. Think of it as being treated like a return variable from the custom tag. CF does perform the closing tag execution and can display a manipulated version of the variable; however, before that second execution's output is displayed, CF will display the value of that variable.

Here's a trick: to stop the display of the original data between the tags, simply set the "thistag.generatedcontent" variable to the empty string.

<cfset thistag.generatedcontent = "">
You can place it at the end of the custom tag code. Since the variable is empty, it will have no impact at all in the first execution of the code caused by the opening tag. In the second execution it'll prevent the automatic redisplay of the data between the tags before the display of the output from that second execution.

Again, it's really tricky and not well documented, but that's the way it works. If you reduce the custom tag to just the following two lines:

<cfoutput>#ucase(thistag.generatedcontent)#</cfoutput>
<cfset thistag.generatedcontent="">
it'll work as expected. The simple output of running call_test.cfm would be:
BETWEEN THE PAIR
which is what we want to achieve when the purpose of the paired tags is to simply perform some processing on the data between them.

Using Rather than Printing the Data
What if the purpose of the tag was to do something with the data between the paired tags without any intention to output it? As an analogy, what if we wanted the paired tag process to process the data as the <CFQUERY> tag does. <CFQUERY> produces no output; rather, it just takes the input to the tag (SQL) and executes it.

It's a fairly straightforward extension of what we just learned. You don't want to create any output in the custom tag code, and again you'd want to set "thistag.generatedcontent" to the empty string.

Using ColdFusion Tags Between the Paired Tags
One last point that's not immediately apparent when first using paired tags is that you're free to use any ColdFusion tags between the paired tags. That's right! You could use CFIF to cause different text to be passed into the "generatedcontent", or even use CFOUTPUT to, in effect, cause CF variables to be passed in.

You could even do a CFQUERY, though it doesn't make much sense in and of itself since it creates no output. If after that query you did some CFOUTPUT processing (even a loop over records), that output would be passed into the custom tag for processing as part of the "generatedcontent" variable.

This opens up some really interesting possibilities!

Summary
I hope this helps explain paired-tag processing. You'll find some coverage of custom tag processing in the Allaire documentation manual, Developing Web Applications with ColdFusion, in Chapter 7, "Reusing Code." You'll find this available within the Help facility in ColdFusion Studio or perhaps on your ColdFusion server if the installation included loading the HTML version of the manuals. Try <yourdomainname>/CFDOCS/dochome.htm> or ask your administrator.

However, you won't get a clear description of what we've covered. This involves more learning by trial and error.

Before concluding, some other topics that are useful to know are the capability to "nest" custom tags (list custom tags inside a pair of other custom tags) and a CF tag related to that sort of processing called CFASSOCIATE. There are also some other "thistag" variables, including one to tell whether the execution of custom tag code is occurring for the opening or closing tag ("thistag.executionmode") and one to tell whether a closing tag has been specified at all ("thistag. hasendtag"). Nested custom tags are covered in the manual as well, and they're also covered in the Allaire class "Advanced ColdFusion Development."

About Charlie Arehart
A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

charles arehart wrote: I didn't address this point in the article, but in case anyone asks, you can use CFMODULE to do nested custom tags. Just note that if you place a single CFMODULE within a pair of others, you'll want to be sure to close the inner CFMODULE, as in or in case brackets don't show up in this commenting system, here is the tag offered using &gt and &lt: <CFMODULE ... \>
read & respond »
CFDJ LATEST STORIES . . .
Opinion: Give ColdFusion Some Room to Breathe
My personal approach has become to to let ColdFusion do what it does best, and no more. No AJAX generation or any of that silly UI stuff. Leave that to the AJAX frameworks, or Flex, or whatever your UI is going to be on the front-end. That's what the UI tool was designed for, CF wasn't
What Is ColdFusion in the Age of Java?
As CFML developers start to learn Java and move into the realm of Spring and Hibernate, it is very important to stop and ask 'What Is ColdFusion?'. ColdFusion, since CFMX, has been a J2EE application running within a J2EE server (JRun, JBoss, Tomcat, Websphere, etc.). This is important
Viewpoint: Not Every ColdFusion Developer Should Be A Flex Developer
I am going to go ahead and contend that although a good number of ColdFusion developers can grasp and understand Flex very well, there are also a good number of ColdFusion developers who have no business going anywhere near Flex. Why do I say this? I am a big fan of Flex. I use it dail
JavaOne 2008: Sun Talks Up its Late-to-the-Party AIR-Silverlight Rival
At Java One this week Sun has been selling its year -old-but-still-upcoming - and definitely late-to-the-party - Adobe AIR- and Microsoft Silverlight-competitive JavaFX Rich Client environment as a potential revenue-generator capable of putting ads on mobile applications and JavaFX Scri
AJAX World - Xceed Launches Microsoft Silverlight 2 Control
Xceed launched Xceed Upload for Silverlight, the commercial offering in support of Microsoft's promising new Silverlight technology. The product is available now for purchase or as a fully functional 45-day trial on Xceed's website. Xceed Upload for Silverlight lets developers add uplo
Microsoft To Keynote 4th International Virtualization Conference & Expo
Mike Neil is general manager for virtualization strategy in the Windows Server Division at Microsoft. Mike is focused on the delivery of the Windows virtualization technology, including Windows Server 2008 Hyper-V, Microsoft Hyper-V Server and Virtual PC 2007. Mike also directs the tec
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE