Ask a Jedi: UDFs in Custom Tags

This post is more than 2 years old.

Nathan asks:

Can you define UDFs inside of CustomTags? I have some repetitive processing I need to do inside of a custom tag and was wondering if this is a valid approach? If so is the UDF local to the custom tag?

Yes, you can. Here is a simple example:

First we will start with the custom tag, which I've given the descriptive name of test3.cfm:

<cfscript> function getNum() { return randRange(1,100); } </cfscript>

<cfparam name="attributes.r_result" default="result" type="variableName">

<cfset result = getNum()*getNum()*getNum()>

<cfset caller[attributes.r_result] = result>

<cfexit method="exitTag">

As you can see, I have a UDF named getNum(). The custom tag uses this to create a result. Now my calling script can simply do:

<cf_test3 r_result="res" />


The UDF does not leak out in the calling page. Just like any other variable defined in the custom tag, it is local to the custom tag only.

In older versions of ColdFusion, I believe the original CF5, you would get an error if you called your custom tag in wrapped more, or with a / at the end of the call. This has been fixed for some time now though.

So the question is - while it works, does it make sense? I would tend to shy away from putting the UDF in the custom tag. It seems like every time I write a function that I'm sure will only be used in one place, I end up needing it a few other places as well. Outside of that though I can't think of any good technical reason not to do this if you feel like you need it.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA