Class active in the menu using include

2

In my php pages I use an include to call a file that contains my menu:

<?php include('../../sidebar-menu.php'); ?> 

Menu file:

   <ul class="sidebar-menu" id="nav-accordion">
             <?php 
                foreach ($lista as $key => $value) {
                  echo '<li class="mt">
                      <a href="/view/DadosIndicadores/index.php?id_tipo='.$lista[$key]['id'].'">
                          <i class="fa fa-bar-chart-o"></i>
                          <span>'.$lista[$key]['nome'].'</span>
                      </a>
                  </li>';
                }
              ?>
    </ul>

How do I insert the class active only in the menu accessed?

    
asked by anonymous 16.11.2015 / 18:28

1 answer

3

PHP has a magic constant that returns you which file is running. This constant is __FILE__ .

Let's say you have the files:
index.php = Home Page
about.php = About the company
contact.php = Contact us

There inside your foreach, you would do some if's like this:

<?php
  foreach ($lista as $key => $value) {
      $ativo = '';

      if($lista[$key]['nome'] === 'Página Principal' && __FILE__ === 'index.php') {
         $ativo = ' active';
      } elseif($lista[$key]['nome'] === 'Sobre a empresa' && __FILE__ === 'sobre.php') {
         $ativo = ' active';
      } elseif($lista[$key]['nome'] === 'Fale conosco' && __FILE__ === 'contato.php') {
         $ativo = ' active';
      }

      echo '<li class="mt'.$ativo.'">
              <a href="/view/DadosIndicadores/index.php?id_tipo='.$lista[$key]['id'].'">
                  <i class="fa fa-bar-chart-o"></i>
                  <span>'.$lista[$key]['nome'].'</span>
              </a>
            </li>';
  }
?>

This is just a code hint. There are several ways to write this ... I gave a very simple and not very elegant suggestion, just so you can understand the idea of what you need.

It's up to you to improve writing! ^^

    
16.11.2015 / 18:52