Welcome!

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:

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

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
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...