[php] How add class='active' to html menu with php

I want to put my html navigation in a separate php file so when I need to edit it, I only have to edit it once. The problem starts when I want to add the class active to the active page.

I've got three pages and one common file.

common.php :

<?php 
$nav = <<<EOD
   <div id="nav">
        <ul>
           <li><a <? if($page == 'one'): ?> class="active"<? endif ?> href="index.php">Tab1</a>/</li>
           <li><a href="two.php">Tab2</a></li>
           <li><a href="three.php">Tab3</a></li>
       </ul>
    </div>
EOD;
?>

index.php : All three pages are identical except their $page is different on each page.

  <?php
     $page = 'one';      
     require_once('common.php');
    ?>
    <html>
       <head></head>
       <body>
          <?php echo $nav; ?>
       </body>
    </html>

This simply won't work unless I put my nav on each page, but then the whole purpose of separating the nav from all pages is ruined.

Is what I want to accomplish even possible? What am I doing wrong?

Thanks

EDIT: When doing this, the php code inside the li don't seem to run, it's just being printed as if it was html

This question is related to php

The answer is


why don't you do it like this:

in the pages:

<html>
   <head></head>
   <body>
      <?php $page = 'one'; include('navigation.php'); ?>
   </body>
</html>

in the navigation.php

<div id="nav">
   <ul>
      <li>
          <a <?php echo ($page == 'one') ? "class='active'" : ""; ?> 
                 href="index1.php">Tab1</a>/</li>
      <li>
          <a <?php echo ($page == 'two') ? "class='active'" : ""; ?> 
                  href="index2.php">Tab2</a>/</li>
      <li>
          <a <?php echo ($page == 'three') ? "class='active'" : ""; ?> 
                  href="index3.php">Tab3</a>/</li>
   </ul>
</div>

You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.

Later edit: fixed syntax error.


Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:

$navigation = new Navigation( 1 );

or

$navigation = navigation( 1 );

A very easy solution to this problem is to do this.

<ul>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>

Which will output

<ul>
  <li class="current"><a href="index.php">Home</a></li>
  <li class=""><a href="portfolio.php">Portfolio</a></li>
  <li class=""><a href="services.php">Services</a></li>
  <li class=""><a href="contact.php">Contact</a></li>
  <li class=""><a href="links.php">Links</a></li>
</ul>

You could use this PHP, hope it helps.

<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>

So a list would be like the below.

<ul>
  <li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
  <li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>

seperate your page from nav bar.

pageOne.php:

$page="one";
include("navigation.php");

navigation.php

if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }

<ul class="nav">
  <li <?php echo $oneIsActive; ?>><a href="pageOne.php">One</a></li>
  <li <?php echo $twoIsActive; ?>><a href="pageTwo.php"><a href="#">Page 2</a></li>
  <li <?php echo $threeIsActive; ?>><a href="pageThree.php"><a href="#">Page 3</a></li>
</ul>

I found that I could also set the title of my pages with this method as well.

 $page="one";
 $title="This is page one."
 include("navigation.php");

and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.


             <ul>

                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
                <li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>

                </ul>

<a href="store/index" <?php if($_SERVER['REQUEST_URI'] == '/store/index') { ?>class="active"<?php } ?> > Link </a>
<a href="account/referral" <?php if($_SERVER['REQUEST_URI'] == '/account/referral') { ?>class="active"<?php } ?> > Link </a> 

The solution i'm using is as follows and allows you to set the active class per php page.

Give each of your menu items a unique class, i use .nav-x (nav-about, here).

<li class="nav-item nav-about"> <a class="nav-link" href="about.php">About</a> </li>

At the top of each page (about.php here):

<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>

Elsewhere (header.php / index.php):

<style>
<?php echo $activeClass; ?> {
    color: #fff !important;
}
</style>

Simply change the .nav-about > a per page, .nav-forum > a, for example.

If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.


CALL common.php
<style>
    .ddsmoothmenu ul li{float: left; padding: 0 20px;}
    .ddsmoothmenu ul li a{display: block;
  padding: 40px 15px 20px 15px;
  color: #4b4b4b;
  font-size: 13px;
  font-family: 'Open Sans', Arial, sans-serif;
  text-align: right;
  text-transform: uppercase;
  margin-left: 1px; color: #fff; background: #000;}
    .current .test{  background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php" class="test">Home  <i>::</i> <span>welcome</span></a></li>
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>"><a href="about.php" class="test">About us <i>::</i> <span>Who we are</span></a></li>
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>"><a href="course.php">Our Courses  <i>::</i> <span>What we do</span></a></li>
</ul><!-- end #dropdown-menu -->

</div><!-- end .span8 -->

add each page
<?php include('common.php'); ?>

  1. $page='one' should occur before you require_once() not after. After is too late- the code has already been required, and $nav has already been defined.

  2. You should use include('header.php'); and include('footer.php'); instead of setting a $nav variable early on. That increases flexibility.

  3. Make more functions. Something like this really makes things easier to follow:

    function maybe($x,$y){return $x?$y:'';}
    function aclass($k){return " class=\"$k\" "; }
    

    then you can write your "condition" like this:

    <a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....
    

I know this is old, but none of these answers are very good (sry ppl)

The BEST way to do it (without writing out convoluted classes) is to compare the current $_SERVER['REQUEST_URI'] to the href of the link. You're almost there.

Try this. (Taken from http://ma.tt/scripts/intellimenu/)

$nav = <<<EOD
<div id="nav">
        <ul>
           <li><a href="index.php">Tab1</a></li>
           <li><a href="two.php">Tab2</a></li>
           <li><a href="three.php">Tab3</a></li>
       </ul>
    </div>
EOD;

$lines = explode("\n", $nav);
foreach($lines as $line)
{
    if(preg_match('/href="([^"]+)"/', $line, $url)) {
        if(substr($_SERVER['REQUEST_URI'], 0, 5) == substr($url[1], 0, 5)) {
            $line = str_replace('><a', ' class="current-menu-item"><a', $line);
        }
    }
    echo $line . "\n";
}

I think you need to put your $page = 'one'; above the require_once.. otherwise I don't understand the question.