Code Reuse

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. Lets call itis start, that means that the tag is being opened. Ifis end, that means that the tag is being closed. This can be checked by setting up an

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 whenexecutionModeis start.

As before, we will want to build the users 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 theattributesscope. Access to them is done by usingattributes.ourVariableName, as in the example below:

cfif thisTag.executionMode EQ start cfset fullName = attributes.firstName & & stName / cfoutput Hello, fullName /cfoutput /cfif

Once again, a greeting has been constructed and were ready to call the tag on the display page. Back indisplayPage.cfm, do the following:

This outputs Hello, Emily Christiansen in the browser.

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

: This argument contains the prefix that the developer will use to reference the tag. This will replace the standard cf_

: 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.

Now its 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.

Emily Christiansen is a software engineer at American Public Media. She works on the Public Insight Network, a platform for newsrooms to engage their sources in a meaningful way. Emily loves learning new programming languages as well as teaching others. She began working with ColdFusion in 2009 and has been a frequent speaker at conferences ever since. Her main interests are code reuse and refactoring. In addition to programming, Emily also enjoys singing, reading, zumba, and video games.

Code licensed under theApache License v2.0. Documentation licensed underCC BY 3.0.

Hosting provided bySilvervine Software