How Add Class='Active' to HTML Menu with PHP

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

Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.

<?php 
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class 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;
?>

The first issue is that you need to make sure that the end declaration for your heredoc -- EOD; -- is not indented at all. If it is indented, then you will get errors.

As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)

To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:

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

It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:

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

Then you can include the logic directly in the string like you originally intended.

Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.

Add class= active to active page using PHP

Figured out the ANSWER...I was over thinking it.

HTML

<ul id="mainnav">
<li class="<?php if ($first_part=="") {echo "active"; } else {echo "noactive";}?>"><a href="#">Home</a></li>
<li class="<?php if ($first_part=="tutorials") {echo "active"; } else {echo "noactive";}?>"><a href="#">Tutorials</a></li>
<li class="<?php if ($first_part=="resources") {echo "active"; } else {echo "noactive";}?>"><a href="#">Resources</a></li>
<li class="<?php if ($first_part=="library") {echo "active"; } else {echo "noactive";}?>"><a href="#">Library</a></li>
<li class="<?php if ($first_part=="our-projects") {echo "active"; } else {echo "noactive";}?>"><a href="#">Our Projects</a></li>
<li class="<?php if ($first_part=="community") {echo "active"; } else {echo "noactive";}?>"><a href="#">Community</a></li>
</ul>

PHP

<?php 
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$first_part = $components[1];
?>

How to set current page active in php

It would be easier if you would build an array of pages in your script and passed it to the view file along with the currently active page:

//index.php or controller

$pages = array();
$pages["offnungszeiten.php"] = "Öffnungszeiten";
$pages["sauna.php"] = "Sauna";
$pages["frauensauna.php"] = "Frauensauna";
$pages["custom.php"] = "Beauty Lounge";
$pages["feiertage.php"] = "Feiertage";

$activePage = "offnungszeiten.php";

//menu.php
<?php foreach($pages as $url=>$title):?>
<li>
<a <?php if($url === $activePage):?>class="active"<?php endif;?> href="<?php echo $url;?>">
<?php echo $title;?>
</a>
</li>

<?php endforeach;?>

With a templating engine like Smarty your menu.php would look even nicer:

//menu.php
{foreach $pages as $url=>$title}
<li>
<a {if $url === $activePage}class="active"{/if} href="{$url}">
{$title}
</a>
</li>
{/foreach}

Set active class automatically to menu

set the active page variable before calling the header file that includes the navbar. note that each page will need a unique name to be referred to as the activePage.

<?php
$activePage="home";
$header = "includes/pageHeader.php";
include($header);
?>

and then in the nav menu for each li insert the php check as follows - if the activePage is the same as the check - it will add the active class to the li.

<li class="navLink <?php if($activePage == "home"){echo"active";}?>"><a href="index.php">HOME</a></li>
<li class="navLink <?php if($activePage == "aboutus"){echo"active";}?>"><a href="aboutus.php">About Us</a></li>
etc....

and and so on through the rest of the links in the nav menu

Setting an active class on a menu item with PHP

<?php
$pages = array(
'PAGE1' => 'FIRST PAGE',
'PAGE2' => 'SECOND PAGE');
?>

<ul class="nav">
<?php foreach ($pages as $pageId => $pageTitle): ?>
<li <?=(($_GET['pg'] == $pageId) ? 'class="active"' : '')?>><a href="?pg=<?=$pageId?>"><?=$pageTitle?></a></li>
<?php endforeach; ?>
</ul>

http://php.net/manual/en/control-structures.foreach.php

Don't repeat yourself -- both li-s are very similar, the only difference is in page ID and title. This approach will really help once you have more than two pages.

Try to keep PHP and HTML as separate as possible -- this will make your life easier once you decide to keep them in separate files (and you will sometimes).

php adding class='active' to menu

OK. At first You can do something like this:

$menu = 'MENU';
$menu = $menu.'SOMETHINGELSE';
print_r($menu); // or return $menu;

In that case it will print / return "MENUSOMETHINGELSE". This is string concatenation. So You can do simple if (as You said you make it before), and write:

$menu = '';
$menu .= 'BEGINNING OF THE HTML';
if($pid==1) {
$menu .= 'class="active"';
}
$menu .= 'REST OF HTML';

Few more words:
But this is not everything. Storing menu in a variable looks really bad. Also outputing HTML like that too. You should try to save only important value in array, and then return / echo menu in loop. For example:

$menu = array(
[0] => array('name' => 'NAME0', 'title' => 'TITLE0', 'url' = '/url0'),
[1] => array('name' => 'NAME1', 'title' => 'TITLE1', 'url' = '/url1')
);

Then generate menu:

foreach ($menu as $m) {
echo '<a href="'.$m['url'].'" title="'.$m['title'].'">'.$m['name'].'</a>';
}

In that case, visual settings are in foreach loop, and menu semantic in simple array. You can store active in that array too.

If You want, You can also take a look at ob_start functions, and use echo, and then return ob_get_contents(), if this is easier for You (http://php.net/manual/en/ref.outcontrol.php).


Remember that on every fragment of PHP code You can escape php.

<?php echo "ASD"; ?>
ASD
<?php echo "ASD"; ?>

This code will output three ASD. You should try to use this technique, and minimize echo ouput of Your application. You can also use it in loops:

<?php foreach ($menu as $m) { ?>
<a href="<?php echo $m['url']; ?>"
title="<?php echo $m['title']; ?>">
<?php echo $m['name']; ?>
</a>
<?php } ?>

I hope You get the idea. If there is much more constant html (as in Your example) this should be much more cleaner to output.


Another thing is storing the menu content inside a function. It is also not a good practice. You should try to switch to object programming style, and try to save this menu array in some sort of global / cache / another object.

In Your case, if someone needs to create two menus on the same site, each time he must call this function, and the whole menu variable is declared from the beginning. While it should be only accessible from the function.

If You dont need to make an object oriented application, or need an easier solution, it is much better to save $menu somewhere else (level higher), and pass it as an argument to for example menu_generator function.

In that case, $menu look like I described it, and You declare function like that:

function generate_menu_html($menu) {
// your menu generation function base on menu array
}

Hope it helps.

Best regards.

How can I set class= active to navigation menu in codeigniter?

You can use $this->uri->segment();

<li>
<a href="<?php echo base_url(); ?>patient/createpatient" <?php if($this->uri->segment(1)=="menu_name"){echo 'class="active"';}?> ><i class="fa fa-users fa-lg"></i> Create Patient </a>
</li>
<?php } ?>
<li>
<a href="<?php echo base_url(); ?>patient/listpatient" <?php if($this->uri->segment(1)=="menu_name"){echo 'class="active"';}?> ><i class="glyphicon glyphicon-list-alt fa-lg"> </i> List Patients </a>
</li>
<?php if( $usertype == "Admin"){?>
<li>
<a href="<?php echo base_url(); ?>user/" <?php if($this->uri->segment(1)=="menu_name"){echo 'class="active"';}?> ><i class="fa fa-list fa-lg"> </i> List Users </a>
</li>


Related Topics



Leave a reply



Submit