Reputation: 9865
I want to add a class=active
to the current page im on with php
class_navigation.php
$menu = array(
'home' => array('text'=>'Home', 'url'=>'?p=home'),
'away' => array('text'=>'About', 'url'=>'?p=about'),
'about' => array('text'=>'Contact', 'url'=>'?p=contact'),
);
class class_navigation {
public static function GenerateMenu($items) {
$html = "<nav>\n";
foreach($items as $item) {
$class ="";
if ($page == $item) {
$class = "class='active'";
}
$html .= "<a href='{$item['url']}' ".$class.">{$item['text']}
</a>\n";
}
$html .= "</nav>\n";
return $html;
}
};
nav.php
<?php
echo class_navigation::GenerateMenu($menu);
?>
index.php
require_once('class/class_navigation.php');
require_once('includes/head.php');
require_once('includes/nav.php');
switch($_GET['p']){
case "home":
$page = 'home';
include_once('pages/home.php');
break 1;
case "about":
$page = "about";
include_once('pages/about.php');
break 1;
case "contact":
$page = "contact";
include_once('pages/contact.php');
break 1;
}
require_once('includes/footer.php');
Upvotes: 0
Views: 77
Reputation: 5484
Remove $page
in switch
and modify your class to this.
GenerateMenu
gets current page with $page = $_GET['p'];
url
value in your array. parse_str(substr($item['url'], 1));
parses this url and you will get $p
equaling to home
, if url is '?p=home'
etc.<?php
class class_navigation {
public static function GenerateMenu($items) {
$html = "<nav>\n";
$page = isset($_GET['p']) ? $_GET['p'] : '';
foreach($items as $item) {
$class = "";
parse_str(substr($item['url'], 1));
if ($page == $p) {
$class = " class='active'";
}
$html .= "<a href='{$item['url']}'".$class.">{$item['text']}</a>\n";
}
$html .= "</nav>\n";
return $html;
}
}
Upvotes: 2