Highlight the current menu item if PHP includes

If I create a nav menu in html and use PHP to include it on every page on my website, how can I highlight the current page if everything I can put on the page includes ("menu.html");

+3
source share
4 answers

You can also write the menu in PHP, since you are already using PHP to load the menu, simply run the if / else statement in the menu items to check if the "href" link in the current page URL matches and set the menu item to "active" .

+6
source

menu.html menu.php -

<ul class="menu">
    <li <?php echo ($page == 'page1') ? 'class="current"' : '';?>> <a href="#">Page1</a> </li>
    <li <?php echo ($page == 'page2') ? 'class="current"' : '';?>> <a href="#">Page2</a></li>   
</ul>

, menu.php,

<?php    
$page = 'page1';
include('menu.php');
?>

, , ,

+10

raw php

<?php 
$currentPage = ''; // should be accessed from $_SERVER
$cssMenu = array('home.html', 'about.html');
if(array_search($currentPage, $cssMenu)) $cssMenu[$currentPage] = 'active';
?>

<ul id="top-menu">
<li class="<?= $cssMenu['home.html'] ?>">Home</li>
<li class="<?= $cssMenu['about.html'] ?>">About</li>
</ul>
+3

divs , - javascript/jquery/whatever . ; Javascript, div ( , div) href, , css .

+1

Source: https://habr.com/ru/post/1778191/


All Articles