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
When growing capacity and power in the data center, the architectural trade-offs between server scale-up vs. scale-out continue to be debated. Both approaches are valid: scale-out adds multiple, smaller servers running in a distributed computing model, while scale-up adds fewer, more powerful servers that are capable of running larger workloads. It’s worth noting that there are additional, unique advantages that scale-up architectures offer. One big advantage is large memory and compute capacity...
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA
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.
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infras...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
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.