Jump to content

A better way to do "current" links?


tmallen

Recommended Posts

I was up late last night hacking on a new (to me) way to do selected links. I got pretty far, but I'd like to hear how you guys do it. Is there a better method than the horribly tedious (and often recommended):

<a class="<?php if($page_id == "home") echo "current "; ?>"

My solution used a GET variable which mod_rewrite transformed into a friendly URL to identify the current page. Then, the navigation was generated from an associative array for which the key was the link ID, and the value for this key was another array with the human link title and another item for the url. Links are generated from this array (which could be fetched from the DB) and the current page ID is checked against each nav item's key.

 

I can post the code later this evening once I'm out of the office.

Link to comment
https://forums.phpfreaks.com/topic/105966-a-better-way-to-do-current-links/
Share on other sites

Well, if you build your navigation dynamically, you can just test the value against page_id...a simple example:

<?php
  $pages = array(
    'home' => 'Home',
    'about' => 'About Us',
    'contact' => 'Contact Us',
  );
  $page_id = $_GET['page_id'];
  foreach($pages as $id=>$title)
    print "<a href=\"index.php?page_id={$id}\"".($id==$page_id?" class=\"current\"":"").">{$title}</a>";
?>

I developed a method myself some time ago, using CSS selectors. The PHP and CSS for the current page would look like this:

 

<?php
$path = $_SERVER['REQUEST_URI'];
//for example "/gallery/summer/"
?>
<style type="text/css">
#menu a[href="<?php echo $path; ?>"] {
	background-color: red;
}
</style>

 

The above CSS applies to any anchor element, where the "href" attribute is set to $path, inside the element with id="menu".

 

This should work in browsers supporting CSS2.

Well, if you build your navigation dynamically, you can just test the value against page_id...a simple example:

<?php
  $pages = array(
    'home' => 'Home',
    'about' => 'About Us',
    'contact' => 'Contact Us',
  );
  $page_id = $_GET['page_id'];
  foreach($pages as $id=>$title)
    print "<a href=\"index.php?page_id={$id}\"".($id==$page_id?" class=\"current\"":"").">{$title}</a>";
?>

I think I like this one best. It's like what I was hacking on last night, but cleaner. I hadn't thought of using the key as both the URL and ID; I was defining the two separately.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.