ColdFusion custom tag for layout example

Last week or so a reader asked if I would quickly demonstrate how I use custom tags for layout. This is something I’ve done for many years now and is typically how I how handle ensuring a web site can easily maintain a consistent look. The idea is simple - use the fact that custom tags can “wrap” other content. How is this done? Consider this code block: <cf_bold>When will the fall season start?</cf_bold>

The custom tag, bold, is used at the beginning and the end of the text block. The last tag is used with a slash just like you see in normal HTML tags that wrap content.

ColdFusion provides a ThisTag scope that provides information about the custom tag. In this case, it tells us if the tag is in a start or end mode. This is done via the executionMode value. So let’s look at a layout custom tag. I call this my Pretty in Pink theme:

<cfif thisTag.executionMode is "start">

<html>

<head> <title>Test</title> </head>

<body bgcolor=”#d95ff3”>

<cfelse>

</body> </html>

</cfif> </code>

The file is split in half with the CFIF statement. The first half runs when thisTag.executionMode is “start”, and the second half will run when it is “end” (or any value really, but that’s the only other value). So to use my layout tag, I can simply do this:

<cf_layout> This is a test. </cf_layout>

Now typically my layout tags perform a bit more work. For example - they typically display a title as well. Consider this modified version:

<cfparam name="attributes.title" default="">

<cfif thisTag.executionMode is “start”>

<html>

<head> <cfoutput><title>#attributes.title#</title></cfoutput> </head>

<body bgcolor=”#d95ff3”>

<cfoutput><h1 style=”color: white;”>#attributes.title#</h1></cfoutput>

<cfelse>

</body> </html>

</cfif> </code>

All I’ve done is defined a variable, attributes.title, and then I use that in both the head area and within an H1 tag. To use this attribute, I just change my files to do this:

<cf_layout title="The 1980s are Superbad!"> This is a test. </cf_layout>

So that’s it. Just a quick note - this can be useful in cases even when you use CSS for everything (markup and layout). Even in 100% pure CSS sites, you still need a head block, you still need to point to the CSS file, etc. So I’d still use the layout tag to get those items into the file.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. 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 https://www.raymondcamden.com

Comments