Active class in the menu using include

Asked

Viewed 290 times

2

On my php pages I use a 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 active class only in the accessed menu?

1 answer

3


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

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 an if’s kind 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 hint of code. There are several ways to write this... I gave a suggestion very simple and not very elegant, just for you to understand the idea of what you need.

I leave it to you to improve writing! ^^

  • Here the use of FILE didn’t bring the file name of the page, but rather brought the file name of the menu sidebar-menu.php. It’s not quite this name that should appear, correct?

  • I forgot you were doing include! Tries to create a variable in the header of the accessed page file, which saves what is in constant _FILE_, before you call include, and then see if include can read this variable... If it works, then just change the _FILE_ if’s. Anyway, why don’t you study using the Twig as a template system?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.