Reputation: 1458
I have separate file (LIB.php) with defined function. This function is called in each page. I want to make it dynamic, when I navigate to one of the pages the page gets active state in the
function get_Navigation(){
$navigation = <<<END
<div class="menubar">
<ul>
<li><a href="index.php"><i class="icon-home icon-large"></i><main>Home</main></a></li>
<li><a href="admin.php"><i class="icon-star icon-large"></i><main>Admin</main></a></li>
<li><a href="cart.php"><i class="icon-money icon-large"></i><main>Cart</main></a></li>
</ul>
</div>
END;
echo $navigation;
}
Upvotes: 3
Views: 156
Reputation: 21062
Use basename($_SERVER['PHP_SELF']);
to get the file name, this will return something like index.php
then, you can add a class to the row or the link to modify its appearance. So your code could look something like this if you want to keep using the heredoc string instead of concatenating several strings:
$isactive = "isactive";
function isactive($filename){
$currentfile = basename($_SERVER['PHP_SELF']);
if($currentfile == $filename) return "active";
}
$navigation = <<<END
<div class="menubar">
<ul>
<li class='{$isactive("prog.php")}'><a href="index.php"><i class="icon-home icon-large"></i><main>Home</main></a></li>
<li class='{$isactive("admin.php")}'><a href="admin.php"><i class="icon-star icon-large"></i><main>Admin</main></a></li>
<li class='{$isactive("cart.php")}'><a href="cart.php"><i class="icon-money icon-large"></i><main>Cart</main></a></li>
</ul>
</div>
END;
echo $navigation;
Note that I'm creating a $isactive
variable which may seem redundant but it's a way of tricking heredoc string to return the functions value instead of just printing its name, but this is really on another scope.
Upvotes: 1
Reputation: 1213
It depends on do you use any framework and are you rewriting the URLs. If we assume that its about plain old PHP without rewrites, you can do something like:
function get_Navigation(){
$current_filename = basename(__FILE__, ".php");
$menuItems = array('index' => false, 'admin' => false, 'cart' => false);
switch($current_filename) {
case 'index': $menuItems['index'] = true; break;
case 'admin': $menuItems['admin'] = true; break;
case 'cart': $menuItems['cart'] = true; break;
}
$navigation = '
<div class="menubar">
<ul>
<li><a href="index.php" class="' . ($menuItems['index'] ? 'selected' : '') . '"><i class="icon-home icon-large"></i><main>Home</main></a></li>
<li><a href="admin.php" class="' . ($menuItems['admin'] ? 'selected' : '') . '"><i class="icon-star icon-large"></i><main>Admin</main></a></li>
<li><a href="cart.php" class="' . ($menuItems['cart'] ? 'selected' : '') . '"><i class="icon-money icon-large"></i><main>Cart</main></a></li>
</ul>
</div>
';
echo $navigation;
}
I'm assuming the index page is named index.php, the admin page - admin.php and the cart page - cart.php
This will append class 'selected' to the active a link.
Upvotes: 0