…posted by davidjmedlock:
Well, in about 7 hours I’m going to be on a plane to Salt Lake City, Utah for my first snowboarding trip. I’ve never been snowboarding or skiiing, so this should be interesting. I just hope I don’t break any important members. (I can live with a broken leg. A broken arm might impede my ability to code, though, and I don’t think worker’s comp will cover it.)
Anyway, before I leave Nashville for the weekend, I wanted to post a brief blog on code reuse. I asked a while back what you all wanted to see in my blogs and articles and one reply was that you’d like to see something about creating custom tags. So, here you go. This will be a pretty brief description of how to create a simple tag, but I think you’ll get the point, and I’ll write more on it when I get back.
First of all, any CFM file can be a custom tag. Try the following exercise. Create a file called “customtag.cfm”. Inside that custom tag, do this:
#Attributes.Hello#
Save it to your web root and then create a file called “tagtest.cfm”. This file looks like this:
First let’s examine the customtag.cfm file. Notice that we’re parameterizing (is that a word?) the “Attributes.Hello” variable. The attributes scope is generally only available within custom tags and modules, although there are some exceptions which we won’t get into right now. Notice the second line of our “tagtest.cfm” file. We pass in the attribute “Hello”.
Also notice the name of the tag we’re calling: cf_customtag. ColdFusion custom tags (not CFX tags) are always called using “cf_” and then the name of the file (excluding the extension). You can then pass any attributes that you want into the tag. These attributes are completely defined by you. Just make sure they follow then naming requirements for ColdFusion variables.
So you can see here the very basics of custom tags:
- The name of the tag is “cf_” and then the name of the template file
- The attributes specified in the tag called go into the “Attributes” scope available inside the tag template.
It’s also important to note that if you move “/tagtest.cfm” to “/test/tagtest.cfm” you will get an error saying that the custom tag template was not found. This is because ColdFusion looks in only certain places for custom tags:
- The directory that the current template is in.
- Any custom tag directories specified in ColdFusion Administrator. This means you can use either the default “
CustomTags” directory or specify that your custom tags are in “C:mytags”. This is done from within the Administrator itself.
So there’s a start. Next week, we’ll talk about custom tag encapsulation and returning variables from custom tags. In the meantime you can visit CFLib and KodeFusion Scripts for some free custom tags to examine.