This is quite possibly the neatest trick ever invented for Coldfusion - so hang on to your Cf_hat. I had nearly forgotten about it until someone on CF-Talk mentioned a problem they were having. It seems they were struggling with a CMS system where users were entering hyperlinks that were incorrectly formatted (they lacked URL encoding). The dilemma was how to fix it without requiring action from the user.
The choices were slim and none of them seamless.
Here's the scoop. You probably already know that you can use CFIMPORT to create a library of custom tags (JSP or CF). You do this by designating a folder containing all the tags and a prefix which subsequently becomes a part of your call to the tag. For example, if I had a directory called "foo" with a custom tag called "bar.cfm" in it, I could do the following:
So far so good. We actually end up with a tried and true JSP type syntax. But what happens if we forget the prefix? Can we still call "bar.cfm"?
As it turns out, this works! Now take a moment and let that sink in. How can we use this new found knowledge to fix the problem above? Simple! We create a directory called "htm" (or whatever) and place a tag called "a.cfm" in it. Then we import "htm" without a prefix. When the scripting engine comes across <a it's going to call "A.cfm". All the attributes that exist in the anchor tag are going to be passed to the custom tag in the "attribute" scope. So the following code:
...now outputs the following link....In my test I did something else. I checked for the existence of a "style" attribute. If I didn't find one, I set the style to font-size: 14pt. Here's the sample tag.
If you want to test it, simply create a directory called "htm" in the same folder as your test script and run this code:
Obviously you could use this technique to great effect. You could enforce styles and classes. You could create a click-handler that all URLs would be forwarded through. You could rewrite boldface, italics, font tags - virtually any tag with attribute type syntax. Obviously some tags would be problematic (like the body tag). Before you go hog-wild you should consider whether this technique is actually necessary. I suspect in many or most cases it is not. Don't use it just because it's neat. It definitely results in something of a management problem with your code. Now, when you look at a page, you can no longer separate out what belongs to CF and what doesn't. That makes it difficult to maintain code using this technique. Still, it might save the day in a few cases.
Muse's Old Blog (Oct. 2002)
Charlie Arehart's "hidden gems" article (Aug. 2002)