ColdFusion Quickie - Leaving an include

This post is more than 2 years old.

Did you know that you can "leave" a cfinclude and return to a calling template? This may be useful in cases where you realize you no longer need to run the rest of the cfinclude and simply with ColdFusion to carry on back in the calling document. Consider the following simple example:

<h1>Pre cfinclude</h1>

<cfinclude template="cfa_test.cfm">

<p> I'm past my include. </p>

My initial template has 2 blocks of text that surround a call to a cfinclude. Here is the cfinclude:

<!--- Should I leave early? ---> <cfif randRange(1,2) is 1> <cfexit method="exittemplate"> </cfif>

<p> Hello from the include. </p>

Now obviously this is a very contrived example, but basically if we 'fail' a 50/50 test we use the cfexit tag to leave the template. If we pass, we keep going on. I've used cfexit many times before, but only inside a custom tag. It never really occurred to me that it could possibly be used within templates as well. The idea came up in a meeting last week and I tested to confirm it works as advertised.

To be clear, the example above is kinda dumb. If you really were going to leave immediately it would perhaps make sense to move the check to the calling template so you don't bother even including it. But hopefully you can get the idea. cfexit is one those tags that doesn't get a lot of usage in most applications, but it can definitely be useful.

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