Building Site Site-Wide Links With ColdBox
Today, we're going to look at using ColdBox to build site-wide links and a global menu. This post assumes you have ColdBox successfully running and are using the standard folder structure for ColdBox.
The first thing we need to do is register an implicit event so we can build our Exit Event Handlers (xeh) for the site. The xeh variables will let us use the links site-wide and have a single point to update the links, should we need to later.
If you open up your Coldbox.cfc, you will see a requestStartHandler. We're going to set this to "general.onRequestStart". You could use any event handler, but we're going to use "general" for this example. Now every request will now run "onRequestStart" in the "general" event handler, before any other code is run. Think of it as a global pre-event.
Next, let's open up general.cfc and add the following function:
<cffunction name="onRequestStart" returntype="void" output="false">
<cfargument name="event" required="true">
<cfscript>
xeh = {
home = ""
,services = {
index = "services"
,consulting = "services.businesslaw"
,webdesign = "services.webdesign"
,seo = "services.seo"
}
,about = "about"
,faq = "general.faq"
,contactus = "contactus"
,videos = "videos"
};
event.setValue("xeh", xeh);
</cfscript>
</cffunction>
What this will do is build a struct, xeh, with our different links. Since we put this into the event object, we'll be able to use this anywhere, including our views.
The next step we're going to do is build our menu. Open up your layout file and let's add the following line where we want the menu to display:
<cfoutput>
#renderview(view="menu")#
</cfoutput>
Then go into your /views/ folder and create menu.cfm. This file is where we will build the actual menu. Let's use this menu to utilize the xeh we build above:
<cfoutput>
<ul class="dropdown">
<li><a href="#event.buildLink(rc.xeh.home)#">Home Page</a></li>
<li><a href="#event.buildLink(rc.xeh.services.index)#">Services</a>
<ul class="subnav">
<li><a href="#event.buildLink(rc.xeh.services.consulting)#">Consulting</a></li><br />
<li><a href="#event.buildLink(rc.xeh.services.webdesign)#">Webdesign</a></li><br />
<li><a href="#event.buildLink(rc.xeh.services.seo)#">SEO</a></li><br />
</ul>
</li>
<li><a href="#event.buildLink(rc.xeh.about)#">About</a></li>
<li><a href="#event.buildLink(rc.xeh.faq)#">F.A.Q.</a></li>
<li><a href="#event.buildLink(rc.xeh.contactus)#">Contact Us</a></li>
<li><a href="#event.buildLink(rc.xeh.videos)#">Videos</a></li>
</ul>
</cfoutput>
What this is doing is using the xeh links to construct the links. Now, as long as we build each function in our event handlers to accept the incoming requests, our links will work. Additionally, in any of our views, we can display links, and they will point to the correct location. For example:
Then if you need to change a link destination, you can just open up your "general.onRequestStart", update the struct, and site-wide your links will be updated.
