This blog is now obsolete. Go to scott.arbeitman.id.au for all new content.

Site Layouts and Application.cfc

| Sunday, April 22, 2007
A common problem for any site developer is maintaining a consistent layout across pages. Many frameworks have been designed to simplify this. Model-Glue, for example, can handle this by having the site template as the last view included in the response cycle. This a heavy approach if all you want to do is view decoration.

Let's take a look at solving this using the onRequest method in Application.cfc to capture our outputted content, and then placing it within a template. Here's a skelteton onRequest method:


<cffunction name="onRequest">
<cfargument name="thePage" type="string" required="true" />
<!--- Magic will happen here --->
</cffunction>


For those of you familiar with onRequest, you'll know that if we don't manually included the requested page, ColdFusion won't send any content to the browser. This might strike some people as odd, but it opens a world of possibilities. For example, see my previous post on using Application.cfc as the application controller in an MVC framework.

In this case, instead of invoking a method within the Application.cfc, we'll store what ColdFusion would have outputted into a variable using the cfsavecontent tag. We'll then include another .cfm page, which will have access to all the variables in the onRequest function, including the just-saved content of the included page. Thus, the onRequest magic looks like this:


<cfsavecontent variable="contentForLayout">

<cfinclude template="#ARGUMENTS.thePage" />

</cfsavecontent>

<cfinclude template="Layout.cfm" />


Now, the code within Layout.cfm has access to the contentForLayout variable which contains the dynamic region of your page. A simple layout could simply output the content within the HTMl body:


<html>

<body>

<cfoutput>#contentForLayout#</cfoutput>

</body>

</html>

Naturally, you've have a much more complex layout, where you'd include Javascript, stylesheets, a header, footer, etc.

Another very important consequence of this is that your Layout.cfm has access to all the variables available within your Application.cfc so there is no reason which your layout cannot content dynamic content.

2 comments:

mlong said...

You can use cfsavecontent in a .cfm file to gather your content, then include the "master" file at the end just as well. Using application.cfc as a template tends to short-circuit using application.cfm/.cfc for global settings, as it's intended.

Anonymous said...

Good post.