How do i implement a dynamic navigation in php?
e.g
Home | about | contact | faq | tutorials
i need to automatically generate the links dynamically respectively to each page without much script. e.g i should have all the links without manually entering the links to each other page?
If you just want to display a menu for a known set of pages without re-architecting your current code, how about this:
<?php
$pages = array(
'index.php' => 'Home',
'about.php' => 'About',
'contact.php' => 'Contact',
'faq.php' => 'FAQ',
'tutorials.php' => 'Tutorials',
) ;
$currentPage = basename($_SERVER['REQUEST_URI']) ;
?>
<div id="menu">
<ul id="menuList">
<?php foreach ($pages as $filename => $pageTitle) {
if ($filename == $currentPage) { ?>
<li class="current"><?php echo $pageTitle ; ?></li>
<?php } else { ?>
<li><?php echo $pageTitle ; ?></li>
<?php
} //if
} //foreach
?>
</ul>
</div>
Put this in its own file, say menu.php, and then include it in each page. Then you can style your menu with CSS.
i agree with the first solution even if its a bit simply. For me you have to split your website into some script where you include your navigation script like the second solution.
but if you really want to make a dynamic navigation, your data cant be write in a file and they are stock in a database or on an xml file....
to do that you have to create a class or a function who parse your data and create array like first solution.
/* header.php (main header template)*/
<html>
<head>
...
</head>
<body>
<div id="mainMenu">
<?php echo Navigation::getNav($databaseCnx);?>
</div>
and in another script you have to create a class who manage the data
<?php
class Navigation{
static function getNav($cnx){
$menuList = '<ul>';
$dataFromDataBase = $cnx->getArray('MySqlRequest');
foreach($dataFromDataBase as $menu) {
$menuList .='<li>'.$menu->name.'</li>';
}
$menuList .= '</ul>';
return $menuList;
}
}
i write it fast but i hope i can help some who look for tips to create dynamic menu.
It seems that you want to include a menu file in all your pages.
You can use include().
In all your pages:
<html>
<body>
<?php include('navigation.php'); ?>
Contents of this page here...
</body>
</html>
And in navigation.php:
<div id="mainmenu">
Home | About | etc...
</div>
This way you can update your navigation menu just once for all your pages.
Related
I am creating a website using HTML/bootstrap and to reduce the repetition of same code I tried using PHP include for footer and sidebar, like this:
<html>
<body>
<?php include('navigation.php'); ?>
Contents of this page here...
<?php include('sidebar.php'); ?>
<?php include('footer.php'); ?>
</body>
</html>
I wanted to do the same thing for navigation menu also, But as the highlighted links changes with each page I am not sure how to change that dynamically.
Since I am using bootstrap just need some method by which I can manipulate the class="active" in the menu links.
(NB: new to php.)
There are tho easy ways to do that. The best way to me is to put the contents of your navigation.php file in a function which has an argument. Then you call the function after your include and you pass as argument a number or a string which represents the item you need to put as active.
Your function then would be something like this:
<?php
function displayNavBar($activeItem){ ?>
<li class="">
<ul class="" > <li <?php if($activeItem=="Home"){echo "class='active'";}?>>
Home</li> <li>contact</li> <li class="active">privacy</li> <li>about</li </ul> </li>
<?php } ?>
Obviously I have written the cose only for the first item, you need to do the same with the others. And then in your file you have to call the function created:
displayNavBar("Home"):
I'm not sure about the structure of your site, but usually you would read the current url and set the active class according to that. So using, for example:
$current_page = $_SERVER['PHP_SELF'];
If you were at /index.php, then you would have
$current_page = '/index.php';
Then it is a simple matter of saying
<li<?php echo $current_page=='/index.php' ? ' class="active"' : ''; ?>>Home</li>
<li<?php echo $current_page=='/about.php' ? ' class="active"' : ''; ?>>About</li>
This is just an example. Set the current page as above, see what the result is using echo, then set the link as below.
I'm trying to figure out how to add a css class to a <li> tag in my menu navigation. I'm using a template that gets included on every page of site. In the template is the menu navigation code. I need to set the css class on the <li> for the corresponding active page using PHP_SELF I presume?
Navigation looks like this
And this is what it should look like when the page is displayed that corresponds to the page that was clicked in the navigation menu.
Here is the navigation menu code
<!-- MENU BEGIN -->
<div id="menu">
<ul id="nav">
<li>Home</li>
<li <?php echo $class_current; ?>>Technician</li>
<li <?php echo $class_current; ?>>Programming</li>
</ul>
</div>
<!-- MENU END -->
Here is the PHP function I am trying to create
function classCurrent(){
if(dirname($_SERVER['PHP_SELF']) == true) {
echo ' class="current"';
}
else {
echo '';
}
$current = classCurrent();
return $current;
}
I know this is possible, I just can't figure it all out yet.
You may try specifying some base class that has variables for the corresponding menus. So like if you are requesting the technician page:
Class Activmenu {
public $technician = true;}
alternatively you may use superglobal variables but this is safer. And in the menu you can check for the true item
if(Activemenu->technician)? echo'class="activeclass"' : 0;
Checking urls you will run into problems, if later on you have to modify your url structure.
So it is really simple actually to do this. All that needs to be done is have a variable set on the active page above the <html> tag preferably.
Example:
<?php $currentPage = 'technician';
<html>
So now we have this variable set on the technician page above the html tag. Now to call it in the template page on the navigation menu <li> all that needs to be done is the following.
<?php if ($currentPage=="technician") echo " class=\"current\""; ?>
Now just need to repeat this step for each page of the website.
This was also answered here PHP navigation menu
and a real good tutorial on how to do it is here http://alistapart.com/article/keepingcurrent
As a result the navigation code will end up looking something like this
<!-- MENU BEGIN -->
<div id="menu">
<ul id="nav">
<li<?php if ($currentPage=="home") echo " class=\"current\""; ?>>Home</li>
<li<?php if ($currentPage=="technician") echo " class=\"current\""; ?>>Technician</li>
<li<?php if ($currentPage=="programming") echo " class=\"current\""; ?>>Programming</li>
</ul>
</div>
<!-- MENU END -->
In my html page, I use a PHP include to insert my site-wide header:
<?php include 'header.php'; ?>
Here is the code in header.php:
<div id="header">
<div id="navigation">
<ul>
<li>home</li>
<li>about us</li>
<li>competition</li>
<li>media</li>
<li>sponsors</li>
<li>contact us</li>
</ul>
</div>
</div>
Here is the CSS in the header of the HTML document:
#nav_about { color:#4c005c; }
The "active" class in the inserted code is to change the color of that link to signify what page you are on. That functions fine, as "active" is defined in the CSS document linked to the html file. I want to modify the color of a particular link depending on what page it is included in. Thing is, the CSS on that page (the one defining #nav_about) does not apply when I test it out. The include works fine though.
In summary, I need to find a way to modify a site-wide snippet of HTML that is inserted via a PHP include with CSS on that page it is inserted in.
I am new to HTML and PHP, so I assume it is some lack of knowledge here.
A simple way to do change the class of the HTML element based on the current page you are on in PHP might look something like this:
<?php
$nav_links = array(
'/index.php' => array('id' => 'nav_home', 'label' => 'Home'),
'/about_us.php' => array('id' => 'nav_about', 'label' => 'About Us'),
// and so on for each link
);
?>
<div id="header">
<div id="navigation">
<ul>
<?php
foreach ($nav_links as $href => $link_info) {
if ($_SERVER['REQUEST_URI'] === $href) {
?>
<li><?php echo $link_info['label']; ?></li>
<?php
} else {
?>
<li><?php echo $link_info['label']; ?></li>
<?php
}
}
?>
</ul>
</div>
</div>
Here you would just apply class=active for the link that corresponds to the currently viewed page. This also makes it really easy to separate out you page/link configuration if you so desire.
Sounds like a selector specificity issue. What's the CSS for your navigation links?
If it's something like #navigation li {color: #abc}, that will take priority over the #nav_about selector.
Selector specificity is ranked by the number of ids, classes, and elements in each.
1 id + 1 element > 1 id.
Increase the specificity of the #nav_about selector (e.g. change it to #navigation #nav_about) and you should be fine.
Try using the traditional way, inside the PHP tags,
<?php
echo "<link rel='stylesheet' href='css-filename.css' type='text/css'>";
?>
I am using php includes to limit redundancy on my pages, how can I have my navigation have the current page selected with say a certain color for the HOME button when my navigation is called from a header.php file.
If i were to say to add a "active" class to the home.php item and add a style so it looked different, that would happen across the board for all my pages, which is why I am using includes in the first place, how can I have one header.php file with my navigation, that also allows each page the ability to show the current page you are on reflected in the navigation?
This is the nav portion of the header.php file
<ul>
<li>About Us</li>
<li>Portfolio</li>
<li>News</li>
<li>Contact</li>
</ul>
This is the index.php file that the header.php file is included in
<?php
include("includes/header.php");
?>
<div class="span-8" id="welcome">
<p>Lorem ipsum</p>
</div>
<div class="span-16 last" id="slideshow">
<img src="images/introImage1.png" alt="fountain">
<img src="images/introImage2.png" alt="bench">
<img src="images/introImage3.png" alt="bridge">
</div>
<?php
include("includes/footer.php");
?>
Try this:
<ul>
<?php
$pages = array('index.php' => 'About Us', 'portfolio.php' => 'Portfolio', 'news.php' => 'News', 'contact.php' => 'Contact');
foreach($pages as $url => $title) {
$li = '<li ';
if($_SERVER[ 'PHP_SELF' ] == $url) {
$li .= 'class="active"';
}
$li .= '>' . $title . '</li>';
echo $li;
}
?>
</ul>
Another option would be to set an attribute against the body tag, and then use a matched pair to change the styling of any number of elements.
So, on your main (home) page, you may have:
<body id="home">
Home
About Us
Then, within your CSS have:
body#home a.home , body#about a.about {
color:#999;background-color:#000; }
And, yet another option would be to include a single CSS statement inside the actual page.
<style type="text/css">
a[href="<?php echo basename( $_SERVER['PHP_SELF'] ); ?>"] ,
a[href="<?php echo $_SERVER['PHP_SELF']; ?>"] {
/* Styles for Current Page Links */ }
</style>
Of course, that is dependent on the browser being able to use that CSS Selector.
And, if you want to be completely sure that all links to the file are covered (including full URIs), then also include the following selector:
a[href="http<?php
echo ( $_SERVER['HTTPS'] ? 's' : '' ).'://'.
$_SERVER['HTTP_HOST'].(
( $_SERVER['HTTPS'] && $_SERVER['SERVER_PORT']!=443 )
|| ( !$_SERVER['HTTPS'] && $_SERVER['SERVER_PORT']!=80 ) ?
':'.$_SERVER['SERVER_PORT'] : '' ).
$_SERVER['PHP_SELF']; ?>"]
UPDATED: Corrected PHP Variables to use.
I have this code in top.phtml which displays my menu items in my Magento store:
<div class="header-nav-container">
<div class="header-nav">
<h4 class="no-display"><?php echo $this->__('Category Navigation:') ?></h4>
<ul id="nav">
<li <?php if(!Mage::registry('current_category')) { echo 'class="level0 active"'; } else { echo 'class="level0"'; } ?>><span><?php echo $this->__('Home') ?></span></li>
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php echo $this->drawItem($_category) ?>
<?php endforeach ?>
<li <?php if(!Mage::registry('current_category')) { echo 'class="level0 active"'; } else { echo 'class="level0"'; } ?>><span><?php echo $this->__('Sale Items') ?></span></li>
</ul>
</div>
I have an extra li at the bottom which displays another page. The problem I have occurs when I click the ‘Sales Item’ page: its link becomes active but so does the home page link. How can I prevent the home page link from appearing active?
I’ve added a screenshot to show the problem:
Screenshot
The lines for Home and Sale Items are both outputting an active category link when the current category is not defined, via the code if(!Mage::registry('current_category')). Instead of checking the category, check the current controller/action.
Here's a list of URL functions (for getting the controller/action):
http://docs.magentocommerce.com/Mage_Core/Mage_Core_Model_Url.html
Code like this should work. It depends on whether or not catalogsale is the identifier for a custom controller or action, which depends on your setup:
if ($this->getRequest()->getControllerName() == 'catalogsale')
// Output active class declaration
/* Otherwise, try looking at the action name. */
if ($this->getRequest()->getActionName() == 'catalogsale')
// Output active class declaration
I ended up fixing this using some javascript. I added this to the new page:
<script type="text/javascript">
Event.observe(window, 'load', function() {
$$('li.active').invoke('removeClassName','active');
$$('li.newmenu').invoke('addClassName','active');
});
</script>
The new menu item should have a class of 'newmenu' for the above code to work.