I'm still a few more weeks away from re-launching the new jasongraphix, but I've been making great progress with Movable Type and learning lots of new tricks. One of my goals with the re-design was to make the site as dynamic as possible by breaking the design into independent php modules that I can include anywhere. One such module, actually contains the menu for my site, and I ran into a minor problem last night. The menu is actually an unordered list that depends on an id="active" identifier to change it's style.

If the menu was actually copied onto every page, I would only have to place the identifier on whatever li was active and be done with it. With the menu in a php file that is included on every page this is a little more difficult. I originally thought I could pass a variable to the include to let it know what menu item to affect, but I knew there had to be a better way, to contain everything in the menu include.

The first idea that came to mind was the php function PHP_SELF. PHP_SELF can be used to get the URL of the page that the browser is on. For Instance, if we were at
http://www.jasongraphix.com/archive/directory/directory/index.php and used:

<?php echo ($_SERVER[PHP_SELF]); ?>

We would see the string:
/archive/directory/directory/index.php

Ok, so that's a neat trick. The problem was breaking a good variable like "archive" out of that mess. I know I could do this by writing a regular expression, but I REALLY don't like regular expressions. I infact loath regular expressions. Sorry Nathan.

The solution: explode()
My inner B&B voice says "Fire,fire,fire heh,heh,heh".
Explode actually takes a string (like our long URL) and brakes it into an array of values by a specified character. In our case that character is "/".

With that in mind, I was able to write up a function to get the variable I needed:

<?php 
$target = $_SERVER[PHP_SELF];
$foo = explode('/', $target);
$menupage = $foo[1];
?>

With menupage defined, I can then write up my menu like:

<ul id="navlist">
   <li<?php if($menupage==""){echo(' id="active"');}?>>
      <a href="/">Home</a></li>
   <li<?php if($menupage=="archive"){echo(' id="active"');}?>>
      <a href="/archive/">Archive</a></li>
   <li<?php if($menupage=="portfolio"){echo(' id="active"');}?>>
      <a href="/portfolio/">Folio</a></li>
   <li<?php if($menupage=="artwork"){echo(' id="active"');}?>>
      <a href="/artwork/">Artwork</a></li>
   <li<?php if($menupage=="about"){echo(' id="active"');}?>>
      <a href="/about/">About</a></li>
   <li<?php if($menupage=="resume"){echo(' id="active"');}?>>
      <a href="/resume/">Resume</a></li>
</ul>

And viola! A completely dynamic menu include that automagically finds out where it's at, and makes my menu reflect it by inserting a much needed id="active" identifier.