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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
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.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.