ColdFusion and Whitespace – Part 3

So far we have looked at ways of controlling chunks of whitespace inside a page but many developers find that most of their cfprocessing and therefore their whitespace is at the top of their page. This is great from a whitespace suppression perspective, we can just reset the output buffer. You can do this with cfcontent and the reset option <cfcontent reset=”true”> will erase everything in the output buffer.

Christian Cantrell posted way back in 2003 of a great little way to access the underlying Java architecture of CF to do the same thing.


There are a few other neat tricks out there to help you put your CF output on a diet.
We use CF_Accelerate all over the place to cache some of our slower code. As well as doing that, it can also clean out some of the whitespace in the cached content before it is cached.

Now that we have the tools to help us attack whitespace, lets have a look at some examples of good and bad code from a whitespace perspective.

The main cause of whitespace is the gaps between tags. When you end a tag, CF looks a the gap between it and the next tag and it decided that this is not CF code to be executed and thus returns it to the browser.

Below is a simple loop that displays a users name if the display flag is set to true. If you were to run this on a standard cf page you would get about five blank lines between each name. These come from the tabs and the new line characters around the ColdFusion tags.

#q.firstname# #q.lastname#

Lets use cfsetting to put this on a diet

#q.firstname# #q.lastname#

Now as Jeff Coughlin pointed out in his comment to part 1, this is very old school – it was the sort of stuff I was coding back in CF4.5 to reduce the whitespace in my pages but it is still very valid today. Yes it does make it a little more code when you first write it but it much lighter.

If you want to go one step further, CFScript is the ultimate in control. Only the characters that you tell it to return make it to the browser.

for(i=1;i lte q.recordCount;i=i+1)

" & q.firstname[i] & " " & q.lastname[i] & "


I am sure that someone is going to tell me I could have removed some of the formatting in this example and brought it down to just three lines of code but I wanted to put it all in so you know what you are getting into if you take the cfscript route.

How do I make the choice? Well for me it is easy. If there is a chunk of code that generates a tonne of whitespace and it is on every page then it is a candidate for converting into either straight CFScript or some for of serious whitespace suppression.

Take the calendar on this page, it uses a lot of whitespace. The whole control is dynamic so why not write it in cfscript. It will take some time to get it just right and it will not be as easy for novice ColdFusion developers to debug but it will be much lighter on your page.

The next target on our whitespace hitlist will be CFCs so stick arround…