2

If there are many pages share a same menu

    include_once('common-menu.php');

But the menu should have some different for different page

Page A

  <ul class="nav navbar-nav">
    <li class="active"><a href="a.php">A Page</a></li>
    <li><a href="b.php">B Page</a></li>
  </ul>

Page B

  <ul class="nav navbar-nav">
    <li><a href="a.php">A Page</a></li>
    <li class="active"><a href="b.php">B Page</a></li>
  </ul>

I only know two solutions.

Solution 1: Server side to detect the URL then determine the output

  <ul class="nav navbar-nav">
    <li class="<? echo 'active'; ?>"><a href="a.php">A Page</a></li>
    <li class=""><a href="b.php">B Page</a></li>
  </ul>


  <ul class="nav navbar-nav">
    <li class=""><a href="a.php">A Page</a></li>
    <li class="<? echo 'active'; ?>"><a href="b.php">B Page</a></li>
  </ul>

Solution 2: Use js/jquery to detect the URL, and then change the class by js/jquery after the page loaded.

What is the best practice for this problem?

Is there any non-programmatic solution so that I don't need to use if/case/map to determine the active item?

iConnor
  • 19,997
  • 14
  • 62
  • 97
CL So
  • 3,647
  • 10
  • 51
  • 95

2 Answers2

2

There is an almost pure css solution but it's not ideal. Output the url as a parent id and use selectors to handle the rest. The downsides to this is it becomes tedious if you need to add a lot of navigation items. It would be much better to use one of the above solutions.

PHP

<div id="<? basename($_SERVER['SCRIPT_NAME'], ".php") ?>">
    <ul class="nav navbar-nav">
        <li><a href="a.php">A Page</a></li>
        <li><a href="b.php">B Page</a></li>
    </ul>
</div>

CSS

#a .nav a[href$='a.php'],#b .nav a[href$='b.php']{    
    color:red;
}
bmasterson
  • 269
  • 1
  • 6
1

On the PHP side, you could do something like this using the built-in PHP currPage() function:

<li class="menu-item <?php chk_active('myprojects.php');?>"><a href="myprojects.php">Projects</a></li>
<li class="menu-item <?php chk_active('invoicehistory.php');?>"><a href="invoicehistory.php">Invoice History</a></li>

And the chk_active() function looks like this:

function chk_active($chkPage){
    if (currPage()==$chkPage) {
        echo 'active';
    }else if (currPage()=='project.php' && $chkPage=='myprojects.php'){
        echo 'active';
    }
}
cssyphus
  • 37,875
  • 18
  • 96
  • 111