You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Paired Custom Tags

Paired Custom Tags

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:

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:


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:

This is a set of data that will be processed by the custom tag.

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.

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>
  • <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:


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:

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:

Between the pair

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:

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>
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>


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>


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

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:

<cfset thistag.generatedcontent="">
it'll work as expected. The simple output of running call_test.cfm would be:
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!

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."

More Stories By 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.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
charles arehart 02/21/03 01:51:00 PM EST

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 &ampgt and &amplt:

<CFMODULE ... \>

@ThingsExpo Stories
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.