Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Handling Site Layouts in ColdFusion with Layout Components

A flexible way to handle layouts for your sites

Most sites have similar issues related to the site layout. I have seen many solutions that solve some challenges related to layout, but fail to handle others elegantly. I have found that using layout components elegantly solves all of the layout problems I have faced.

What Do I Want?
Here are my goals for handling layouts. I want to:

  • Make edits to the layout in one place
  • Easily switch layouts (per page, section, etc.)
  • Switch to non-HTML formats (PDF, Word, etc.)
  • Use any ColdFusion tags (like cfflush)
  • Do without mappings and relative paths
  • Add HTML to the <head>
  • See all of the layout in one file
  • Avoid passing all page calls through one file (like index.cfm)
Here is a quick example of switching to non-HTML formats: I didn't have to switch the format using the URL, but it made a handy example. This makes "download to Excel" functionality a breeze.

As you will see, layout components also make it easy to use a different layout on your home page than on other pages. Similarly, the login page for your admin section can use your default site layout (instead of the admin layout).

Include Interlude
Before I discuss layout components, let me explain why I don't use more "obvious" techniques.

Specifically, I recommend you avoid the temptation to put output code in Application.cfm (and OnRequestEnd.cfm). When a page needs an alternate layout (a pop-up, home page, etc) then you have to add an exception to Application.cfm, which can lead to unwieldy code.

For instance, some programmers use a different layout based on the filename being requested (e.g., "index.cfm" gets a different layout from the rest). This is problematic when you or your client wants to make a quick copy ("index2.cfm") to test a change.

While you could determine layout using the directory structure, this is also limiting. A home page may need a different layout than the rest of the site or the client might decide to change the layout of any page. You should be able to change a layout without moving the page (lest you jeopardize links and bookmarks).

I therefore recommend that you call output code from your page (whether you use layout components or not) to ensure this flexibility. Using layout components doesn't prevent you from including your output from Application.cfm, but I highly recommend that you include your output from your page.

Let's Take a Look
I frequently need to add code to the <head> of just one page. Using <cfhtmlhead> works, but seems clunky. I would prefer code as shown in Listing 1. My home page, using a different layout, might look like Listing 2.

In any event, I must first initialize the layout component:

<cfset layout = CreateObject("component","layouts.default").init()>

This instantiates a layout using layouts/default.cfc (from the root of your site). This can be called from Application.cfm (creating the layout variable doesn't cause any output).

The code for default.cfc is in Listing 3. The code for Home.cfc (the layout used on our home page) would be the same with slightly different HTML.

As you can see, a layout component is just a basic HTML page with some component tags in the mix. Within a week of working layout components, I learned to ignore the cffunction and cfcomponent tags and just see the HTML. You can see the resulting HTML for Listing 1 in Listing 4.

How Does It Work?
As I am sure you can tell by looking at the component code and the resulting HTML, each method of the layout component is called in turn and outputs HTML into the page.

Normally, a CFC shouldn't output anything directly. In this case, however, the whole point of a layout component is output. So, the output of each cffunction is "yes" (where it would normally be "no").

It is important that </head> is at the top of the body() method. This allows me to put HTML into the head of the document by placing the code between layout.head() and layout.body().

Of course, we still need to cover how to switch layouts...

Switch Layouts
You might have noticed that default.cfc has an extends attribute in the cfcomponent tag (look at the first line in Listing 3). That means that it inherits some behavior from the layout.cfc in the same directory (see Figure 1 for an example inheritance tree).

The methods that are common to all of our layout components go here. Among those is the switchLayout() method that we used at the top of our home page to switch to the home page layout (Home.cfc).

If you wanted to switch to a Word layout (to output to Word instead of HTML), you would switch to the Word layout like so:

<cfset layout = layout.switchLayout("Word")>

This would use Word.cfc for your layout, which would be a layout component with very basic HTML and the following tag at the start of the output:

<cfcontent type="application/msword" reset="Yes">

Make sure to call layout.switchLayout() before layout.head(). If you want to take a look at the code for layout.cfc, you can see it in Listing 5.

How Does This Compare?
The usage of layout components that I have described is most similar to using cfinclude to include a header and footer, with some notable advantages. You don't have to worry about using different paths depending on the location of your file. You can see the whole layout in one file, allowing you to easily see where your divs and table cells open and close. You can switch your layout using code in just one place.

More Stories By Steve Bryant

Steve Bryant is the founder and CEO of Bryant Web Consulting LLC (www.bryantwebconsulting.com) and teaches ColdFusion at Breakaway Interactive (www.breakawayinteractive.com). He got his BA in philosophy at Oklahoma State University. Steve, one of the top ColdFusion developers in the country, still has no idea how that led to a career in Web development. Steve blogs at steve.coldfusionjournal.com as one of CFDJ's published bloggers.

Comments (2)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...