Skip to content

Instantly share code, notes, and snippets.

@learncfinaweek
Created November 20, 2012 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save learncfinaweek/4121227 to your computer and use it in GitHub Desktop.
Save learncfinaweek/4121227 to your computer and use it in GitHub Desktop.
Code Reuse - Custom Tags

For displaying code on the front end, another option is to use a custom tag. Custom tags live in their own directory and are prefixed with "cf_". Putting a custom tag on a cfml page will execute the code contained in the tag as if it had been included on the page itself. Start by creating a new .cfm file to house our custom tag. Let's call it greeting.cfm. First, check the executionMode of the tag. If the executionMode is "start", that means that the tag is being opened. If executionMode is "end", that means that the tag is being closed. This can be checked by setting up an if statement like so:

<cfif thisTag.executionMode EQ "start">

<!--- Code to execute when the tag is being opened --->

<cfelse>

<!--- Code to execute when the tag is being closed --->

</cfif>

Because our example is relatively simple, we will focus on the code to be executed when executionMode is "start".

As before, we will want to build the user's full name, which means we will probably want to pass those into the tag. Setting attributes on the tag as if it were any other ColdFusion tag will accomplish this; these are then stored in the attributes scope. Access to them is done by using attributes.ourVariableName, as in the example below:

<cfif thisTag.executionMode EQ "start">
&lt;cfset fullName = attributes.firstName & " " & attributes.lastName /&gt;

&lt;cfoutput&gt;
      Hello, #fullName#
&lt;/cfoutput&gt;

</cfif>

Once again, a greeting has been constructed and we're ready to call the tag on the display page. Back in displayPage.cfm, do the following:

<cf_greeting firstName="Emily" lastName="Christiansen" />

This outputs "Hello, Emily Christiansen" in the browser.

You can also use cfimport to bring multiple tags into your page, and put them in their own namespace. The tag takes only two arguments:

  • prefix: This argument contains the prefix that the developer will use to reference the tag. This will replace the standard "cf_"
  • taglib: This is the path to the tag library, relative to the web root.

Now we can use the import tag to import several tags, and give them a more descriptive prefix.

<cfimport prefix="display" taglib="/path/to/tags" />

<display:greeting firstName="Emily" lastName="Christiansen" />

Now it's easy to see that the greeting tag belongs in the package called display, which gives us a clue as to what the tag does. It displays the greeting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment