Keeping Your Head(er)

While I was playing with the gun show page I also ran into something that annoyed me enough to finally fix it.  Each page on the gun show site had a little navigation header (sort of like tabs) at the top that displayed the current page in bold and had links to the other pages:

Adding new pages is kind of annoying since you have to go into each of the previously existing pages and add the new links.  Further, in adding the new pages I decided to make them “sub pages”, which further complicated matters:

One of the great features of EE is the ability to create templates that you embed in other templates.  So I thought that if I could figure out how to differentiate the different pages I could possibly create a template that determined which item to highlight automatically.  That would solve the problem once and for all, and adding a new page would be as simple as adding the link to the one template.

It turns out that EE has some handy features to let you do this.  If you’ve noticed the URL’s on this site, they’re usually of the form “/basedir/index.php?/group/template”.  The group segment of the URL specifies the “template group,” which is a set of templates that logically go together.  They can be used for a variety of purposes, but I typically use them to organize different weblog (i.e. this page is in the “orglog” group and the gun shows are in the “shows” group).  But EE will let you pull content from multiple weblogs into a single template, which (while powerful), kind of confuses things.

Anyhow, EE lets you access the segments of the URL after “index.php?” using segment variables in your templates.  For example, if the URL is “../index.php?/shows/history” you can reference “segment_1” and get “shows” or “segment_2” to get “history.”  Since I used a unique template name for each “type” of page (main, calendar, details, map, etc), I can examine the second segment to determine which page is being used.  The only exception is the index template, which is implied when no other information is given or if the second segment is unrecognized (which is how EE handles individual pages, by the way; if the last segment isn’t a recognized template it’ll invoke the index template with special parameters which cause the main weblog entries loop to return only the one entry specified in the URL; you can see this by clicking the “Permalink” link below this entry).

So, using the above, you can use EE’s conditionals to check for the template name and decide which is highlighted:

In the short term it would have probably been faster (but a little tedious) just to hard-code the header in each page, but what many people don’t realize is that programmers are lazy.  We’ll spend inordinate amounts of time (just an hour or so in this case, though), figuring out how to automate something that only takes a few seconds if it’s annoying or tedious.

Comments are closed.