XML Style: to close or not to close

written by Geoff Bowers on Saturday, 9 February, 2008 @ 08:32 PM

XML style tags... I'm a sucker for their "completeness". <tag /> -- it's a personal thing. Each to his own you say -- just make sure you write your custom tags to let me have things my way. Custom tags seem to be in the hinterland of ColdFusion development these days, but i just love 'em. If you're going to build them, build them right. Make sure that you can call them in "xml style".

Custom tags have two execution modes, "start" and "end". The current mode is captured in a tag specific variable called thistag.executionmode. When you have a tag that opens and closes it all makes sense -- <tag>blurbage</tag>. The tag actually runs twice: once for the opening tag where thistag.executionmode equals "start" and once for the closing tag where thistag.executionmode equals "end".

It's common to have some conditional logic that separates your tags function into the two modes of execution.

<cfif thistag.executionMode eq "Start">
 ...here start tag magic happens...
</cfif>
<cfif thistag.executionMode eq "End">
 ...here end tag fairy dust is thrown...
</cfif>

Use two ifs, an if-else or a switch -- it doesn't really matter. Just know that the tag is running twice.

Using <tag> just runs the tag in "start" mode. But going "xml style" and using <tag /> automatically runs your tag twice: in start and end modes. That's why you sometimes see tags running their code twice for no good reason -- the creator has neglected to cater for both times the tag gets executed.

If you're like me and you hate having to wrap code in a conditional statement for no good reason, you might like to consider the following snippet. It's a cute little code block you can throw at the top of any custom tag that is designed to run once only.

<!--- allow developers to close custom tag by exiting on end --->
<cfif thistag.ExecutionMode eq "end">
 <cfexit method="exittag" />
</cfif>

Enjoy!

Comments

Permalink: http://blog.daemon.com.au/blog-post/xml-style-to-close-or-not-to-close

Options:

Size

Colors