0

I am trying to make menu with active class for every site.

And I don't know what I am doing wrong. Thnaks for help :D

<li class="nav-item <?php echo $home; ?>">
<a class="nav-link" href="/">Home</a>
</li> 
<li class="nav-item <?php echo $hry; ?>">
<a class="nav-link" href="/hry">Hry</a>
</li> 
<?php
  $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  if($host == 'myurl.com/') {
    $home = 'active';
  }
  elseif ($host == 'myurl.com/hry')  {
    $hry = 'active';
  }
  else {
  $home = 'non-active';
  $hry = 'non-active';
  }
  ?>
Jarda_H
  • 30
  • 7
  • Does this answer your question? [Add class="active" to active page using PHP](https://stackoverflow.com/questions/13336200/add-class-active-to-active-page-using-php) – Robin Singh Oct 13 '20 at 06:32
  • It is not clear what you want to achieve but looking at your code there I see problem lies here: You are setting the variables `$home` `$hry` after your HTML. You should set them before you output html. – Manish Pareek Oct 13 '20 at 06:35
  • Yes :D That was the problem. Thanks – Jarda_H Oct 13 '20 at 06:39

2 Answers2

0

Looking at your code, I see problem lies here: You are setting the variables $home $hry after HTML.

You should set them before you output html. Should be like this:

<?php
  $host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  if($host == 'myurl.com/') {
    $home = 'active';
  }
  elseif ($host == 'myurl.com/hry')  {
    $hry = 'active';
  }
  else {
    $home = 'non-active';
    $hry = 'non-active';
  }
?>
<li class="nav-item <?php echo $home; ?>">
<a class="nav-link" href="/">Home</a>
</li> 
<li class="nav-item <?php echo $hry; ?>">
<a class="nav-link" href="/hry">Hry</a>
</li> 
Manish Pareek
  • 409
  • 5
  • 12
0

You can always write a helper function:

function checkIfActive($route){

    if(strpos($_SERVER['REQUEST_URI'], $route) !== false){
        return "is-active";
    }
    return null;
}

And insert the helper function into your html for every menu item. It will check to see if its active based on the string you put in

<li class="nav-item <?php checkIfActive('string_for_home_url') ?>">
<a class="nav-link" href="/">Home</a>
</li> 
<li class="nav-item <?php checkIfActive('string_for_hry_url'); ?>">
<a class="nav-link" href="/hry">Hry</a>
</li> 

This will be a lot easier for you once you application and menu items start growing

max234435
  • 587
  • 5
  • 18