Home
Tools/Projects
ColdFusion
JavaScript
Articles/Tutorials
Creating Dynamic "onload" Events Using JavaScript
Client-to-Server Communication Using DHTML
Executing a DTS Package from CF/ASP/PHP/SQL
Creating a Custom ColdFusion Tag (101)
Structures
Downloads
Custom Tags
qForms JSAPI
Clients
About

Creating a Custom ColdFusion Tag (101)
by Dan G. Switzer, II | 02/16/2000

Introduction

The goal of this lesson is to teach you the basic concepts of creating a custom tag. I'll cover everything you need to know to build your very first tag. The great thing about a custom tag is building one is no more difficult then building a regular ColdFusion template—there are just some special concepts you have to be aware of. If you've already created custom tags before, don't fret, I'll also be including some helpful tips and tricks in the second lesson that even the most advanced ColdFusion developer can learn from. Most importantly, I hope to cover the three W's—what, why and when you should use custom tags.

What is a custom tag? A custom tag is a ColdFusion template that allows you to build a complex set of actions, that return a result, that display information to the screen or anything else you can do with ColdFusion. If you're familiar with other programming languages, you might be familiar with the term "functions." You can think of custom tags as Allaire's way of allowing you to build "functions" for use in your code. A function is a set of instructions that performs a predetermined action. The nice thing about functions is that any time you need to perform that action, instead of actually re-typing the code, you simply make a call to that "function" and the action is executed. One benefit that custom tags have over functions, is that once your tag is created, you can use it within any template on the server—for that matter you can even redistribute your custom tags to other ColdFusion servers or developers for use on their own servers.

Before we get into actually creating our first custom tag, let's cover why custom tags are extremely important to developing efficient code. The most obvious reason is code re-usability. How many times do you find yourself typing the same lines of code over and over; or for that matter, cutting and pasting the same text over and over. With custom tags, you have the ability to create a single template of code that you can use throughout your entire site; in any template. By centralizing your code in this manner, when the time comes to modify how the process is handled, you only have to make the change in one place. This concept is also called creating "modular" code. This will greatly simplify the amount of work you have to do to your site when a change does occur. Besides creating modular code—which is inherently easier to maintain—custom tags can really help to improve the readability of your code. Take a look at the following two lines, which is easier to comprehend?

Source Code

Hands down, the second line is much easier to follow. It clearly states exactly what action is being taken.

Now that we know what custom tags are, and why we should use them, the next step is determine when we should use them. Fortunately, this is the easy part. Any time you find yourself needing to perform the same action over and over, this is the perfect situation to start the process of creating a custom tag. Since custom tags can be re-used from project to project, any time you come up with a process you know you'll need to repeat in the future, think about how you can turn that into a custom tag. It'll save you a lot of development time down the road. You should now have good grasp on the three W's, so let's actually get started developing our first ColdFusion tag!

Getting Started

The first thing to do when creating a custom tag is to decide what it is you actually want to accomplish. Once you've determined what the actual goal is, then you can start work on the problem. For this lesson, I'll use a problem that most developers run in to at same point in time: removing all the HTML tags from a given string. From time to time, you'll run in to a situation where you need to make sure a string contains no HTML. Whether you're building an discussion board or capturing text to display on the your site, this is a problem most of us have, or will, run in to. To solve the problem, one of two actions can be taken; you can either refuse to accept the string if it contains HTML, or you can simply remove it from the string. For this lesson we're simply going to strip the HTML from the string automatically.

Now that we've determined the exact goal we want to achieve, we need to start a new template that will become our custom tag. I have a default template I like to use for developing custom tags, feel free to cut and paste the code into your documents:

Source Code
NOTE: The first and last lines prevent any additional white space from being outputted on the screen. However, if you choice to keep these lines in your template, any text that you want displayed to the user must be between <cfoutput></cfoutput> tags.

Once you've pasted the above template into a document, you'll need to save the file. Pick a directory on your ColdFusion server that you'll use as a working directory for this lesson. When prompted for the file's name, name the file "stripHTML.cfm".

Now that we've saved the file, let's fill in the "Name", "Written By", "Date" and "Description" information in our template. This will help us to identify exactly what this template does later down the road. You're template should now look something like this:

Source Code
NOTE: To save time, you can cut and paste the description above right into your document.
Create A Working Model

I'm now going to take you through a process, that once you're familiar with writing tags, you can completely bypass—although from time to time you may find yourself doing it anyway. This process will really help you plan out what is actually required to get the custom tag to work. It will also show you how few differences there are between a custom tag and a regular ColdFusion template.

To help you through the process of creating a custom tag, we're going to start off by creating the script so that it functions as a standalone template. Since we already have our goal set—to remove all HTML— and we already know what steps we need to take to do that (see the regular expression above,) let's go ahead and start building the template.

The first thing we want to is set a local variable equal to a string that contains some text which allows includes a few HTML tags. To do this, let's initiate a variable under the "set local variables" section of our template.

Source Code

Now, between our "[begin]" and "[ end ]" sections of our template, let's add the following lines:

Source Code
NOTE: To learn more about using RegEx expression, refer to the ColdFusion User's Guide. There is also an excellent book called "Mastering Regular Expressions" (by Jeffrey Friedl) which is published by O'Reilly books.

Our template should now look similar to the code below:

Source Code

Let's go ahead and execute the template. You should see the words "Hello World!" appear on the screen twice, once in bold print, once in a normal typeface. Now look at the source code. Can you see the difference? The source code should look like the following:

Output

Notice how the second line of the source code does not include any HTML tags—which is exactly the desired result we were after. Now that we know that we have our logic built correctly and the end result is what we were hoping to get, we can actually start converting the template into a custom tag. Once you have some practice at building custom tags, you should be able to skip the above section completely.

Passing Data Between The Template And The Tag

Before we make any more changes to the code, there are a few special ColdFusion scopes that are only to custom tags. A scope is a specific variable "type." For example, the "FORM" scope is where all the form variables available to the current page are stored. The most important two scopes to note are the "Attributes" and the "Caller" scopes. Let's take a detailed look at both of them.

The "Attributes" scope is exactly what it sounds like; it's the scope in which each attribute passed to your custom tag is stored. If we look at the ColdFusion tag "CFOUTPUT", it has four attributes that you can pass to the tag: "query, group, startRow and maxRows." If the CFOUTPUT tag was a custom tag, you'd be able to get to those variables within the CFOUTPUT template by referencing them as: Attributes.QUERY, Attributes.group, Attributes.startRow and Attributes.maxRows. So, when you need to reference attributes passed to your custom tag, you'll append the "Attributes" scope when referencing that variable.

To explain the "Caller" scope, let me first define what ColdFusion considers the "caller." ColdFusion considers the "caller" to be the template that initiates the request to—or "calls"— the custom tag. Therefore, the "Caller" scope provides you complete access to the variables stored in the template which called your custom tag. The caller scope is extremely important since it's your only method of returning values to the calling template.

Building The Tag

Now that you know how to pass information to and from a custom tag, we can now start the process of converting our stripHTML.cfm in to a functioning ColdFusion tag. The first thing we need to do is to remove the unnecessary code that we had inserted for creating the work model. Trim down your template so that it looks like that following:

Source Code

The next thing we need to do is to think about how the custom tag needs to interact with the calling template. Having already determined that our goal is to input a string and output a new string identical to the first, but excluding the HTML, we know that we need to know to things from the calling template: the string to process and the name of the variable to return the new string as. Let's call the attribute for inputting the string, "STRING", and the attribute for outputting the new string as "OUTPUT". To do this, insert the following two lines under the "set default attributes" section of your template:

Source Code

By using the <CFPARAM> tag, we're able to set up default values for tag to use in case the user does not explicitly specify the attributes. In this case, we've told the template that if the attribute "STRING" does not exist, set the value to nothing and if the attribute "OUTPUT" isn't specified then set the value to "cfStripHTML." By setting default values for the attributes we've prevented the developer from having to explicitly define the attributes. In most cases, you'd want to make the "STRING" attribute a required attribute, however for our first lesson, we'll not require it. Part 2 of the lesson will cover advanced topics—such as forcing the developer to providing certain attributes.

Now that we've added the default parameters required, let's also add the attribute definitions into our comment field, under the "ATTRIBUTES:" section. Simply list all the attributes, and a short description. This is not a requirement, but it will be immensly helpful if you ever need to alter or use the tag again. Here's how it might look:

Source Code

Now that we've commented what all the attributes are for, let's integrate them into our routine. Directly after the "[begin] custom tag action" comment, insert the lines:

Source Code

Now we need to return the value store in the sText variable—after all the processing is done—to the calling template. To do this, insert the following lines directly before the "[ end ] custom tag action":

Source Code

Your template should look like something like this:

Source Code

Make sure to save all your changes. Congratulations, you should now have a working custom tag!

Using A Custom Tag

Now that you've built your custom tag, the next thing you need to know is how to use the tag. Copy and paste the following code into a new template then save it to the same directory in which you saved the "stripHTML.cfm" template.

Source Code

Pay close attention to line 17—the bolded line. By simply appending the prefix "<cf_" to our template name* we were able to use the stripHTML.cfm template we created as custom tag. Also, notice how we escape the "STRING" attribute's value in pound signs—this is to ensure that the string is evaluated before ColdFusion sends the value to the custom tag. If we had not wrapped the sText in pound signs, then value within that variable would not have been evaluated and only the string "sText" would have been passed to the custom tag. You should have also got the fact that we're replacing the value of "sText" with whatever the custom tag calculates as it's output. In lesson two, we'll cover a trick to make this easier.

NOTE: Make sure to exclude the file .cfm extension. ColdFusion will automatically know to look for a file ending in the suffix ".cfm".

Go ahead and run the template now. Notice the difference between the "before" and "after" boxes. If every thing worked correctly, the "after" box should not have any HTML in it. Now wasn't that easy? In part 2 of this lesson, we'll concentrate on some techniques that can help you to make more advanced ColdFusion custom tags that are a little more intuitive.

If you have any questions about this article, please feel free to contact the author at dswitzer@pengoworks.com.

Copyright © 2017, PengoWorks.com. All Rights Reserved.