Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

How can I cache the results of a block of ColdFusion code?

The ColdFusion <cfsavecontent> tag is a convenient way to store the results of a block of ColdFusion code. The <cfsavecontent> tag is called with both a beginning <cfsavecontent> and an ending </cfsavecontent> tag. <cfsavecontent> has a single required attribute called variable. This attribute will hold the cached results of the <cfsavecontent> tag.

So now that you know how to call the <cfsavecontent> tag, what does it do? When you wrap a block of ColdFusion code with a <cfsavecontent> tag, the block of code executes, but any output that is generated by the block of code doesn't display to the screen. Instead, the output is stored in the variable that you choose in the varaible attribute of the tag.

<cfsavecontent variable="cachedOutput">
I am going to count to 10!<p>
<cfloop index="loopOn" from="1" to="10">
    <cfoutput>#loopOn#<br></cfoutput>
</cfloop>
</cfsavecontent>

If you want to see the output, you would need to do the following:

<cfoutput>#cachedOutput#</cfoutput>


This question was written by Jeremy Petersen.
It was last updated on February 8, 2006 at 11:27:43 AM EST.

CFML Referenced

<cfsavecontent>
<cfoutput>
<cfloop>

Categories

Caching

Comments

Comment made by J Samland on February 9, 2006 at 1:24 PM
This doesn't really "cache" the results, does it? It just saves the output to a variable. If someone else runs the page, it will rerun the code in the cfsavecontent block.


Comment made by Jeremy Petersen on February 9, 2006 at 1:47 PM
Good point of clarification. It depends on the scope of attribute ‘variable’. By using session or application scope you can persist the "cache" beyond a single page/ person. example: variable="application.cachedOutput"


Comment made by Andrea Classen on February 10, 2006 at 4:36 AM
One alternative that I found helpful, as it caches queries, structures and the like, is cf_elementcache, as far as I know by Johan Coens. That is very good if you still want to have dynamic content but using not-so-quickly changing data from a complex or hand-made query.


Comment made by Sinuy on January 9, 2007 at 10:06 PM
hi J can i 'flush' or 'refresh' the application.cachedOutput at anytime? and how?