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) View Comments

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.


Most Recent Comments
CFDJ News Desk 11/29/05 06:57:35 PM EST

Handling Site Layouts in ColdFusion with Layout Components. 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.

Steve Bryant 11/29/05 12:13:51 PM EST

I haven't used Fusebox 4. From my understanding, though, the restriction on cfflush has been circumvented in Fusebox 4. The need to run al files through index.cfm, however, is central to Fusebox.

@ThingsExpo Stories
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.