So, you have a bunch of links along the top of your page, and you want to highlight the current one when you click on it. Easy enough to do if you copy and paste the entire navbar onto every page and add some CSS to the current tab, but that’s just bad practice! You want to throw the navbar in a layout, and still have it work.
Well, here’s an easy solution! Just drop this in your layout:
<ul id="navbar">
<?php
$pages = array(
'url1' => 'linktext1',
'url2' => 'linktext2',
'url3' => 'linktext3'
);
foreach($pages as $url => $name) {
if($url == $currentPage) echo '<li class="current">'.$name.'</li>';
else echo '<li><a href="'.$url.'">'.$name.'</a></li>';
}
?>
</ul>
<?php
$pages = array(
'url1' => 'linktext1',
'url2' => 'linktext2',
'url3' => 'linktext3'
);
foreach($pages as $url => $name) {
if($url == $currentPage) echo '<li class="current">'.$name.'</li>';
else echo '<li><a href="'.$url.'">'.$name.'</a></li>';
}
?>
</ul>
And make sure you set $currentPage properly. You could use $_SERVER[‘REQUEST_URI’] if your URLs are in the same format (leading and trailing slashes if necessary).
Update: Made a little wrapper function out of this too.
function list_links($links) {
global $currentPage;
foreach($links as $name => $url) {
$class = strtolower($name);
$class = preg_replace('`[^a-z\s]`', '', $class);
$class = preg_replace('`\s+`', '-', $class);
$class = trim($class, '-');
if(ltrim($url,'/') == $currentPage) echo '<li class="',$class,'"><a href="',$url,'" class="selected">',$name,'</a></li>';
else echo '<li class="',$class,'"><a href="',$url,'">',$name,'</a></li>';
}
}
global $currentPage;
foreach($links as $name => $url) {
$class = strtolower($name);
$class = preg_replace('`[^a-z\s]`', '', $class);
$class = preg_replace('`\s+`', '-', $class);
$class = trim($class, '-');
if(ltrim($url,'/') == $currentPage) echo '<li class="',$class,'"><a href="',$url,'" class="selected">',$name,'</a></li>';
else echo '<li class="',$class,'"><a href="',$url,'">',$name,'</a></li>';
}
}
This one adds a class to each <li> too so you can style it in your CSS.
Leave a comment