I'm stuck trying to create a basic navigation system for a site.
I've got a .txt file that I'm trying to put the whole site nav into then I'm looping through line by line and creating nested s. This works fine, but I have two problems:
1-I have a separate navigation in a different div so it's not nested and I don't know how to populate that since it doesn't happen in the first loop.
2-I don't know how to change the class of the parent nav link without using JQuery or manually adding a $parent variable to each page.
Here is my code:
nav.txt
index.php:Home
products.php:Products:2
ace.php:Ace Blade
electrodes.php:Electrodes
megasoft.php:Mega Soft
lletz.php:Lletz Loops
megapower.php:Mega Power:-2
samples.php:Samples
gogreen.php:Go Green:2
wastecalculator.php:Waste Calculator
environmental.php:Environmental Considerations:-2
about.php:About Us
MY NAV FUNCTION:
<?php
function main_navigation()
{
$active_page = basename($_SERVER['PHP_SELF']);
?>
<div class="main_nav">
<ul>
<?php
$nav = fopen("template/nav.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($nav)){
$line = fgets($nav);
list($url, $name, $layer) = explode(":", $line);
echo "<li>";
if ($active_page == $url) {
echo "<div class='active'>".$name."</div>";
}else{
echo "<a href='".$url."'>".$name."</a>";
};
if ($layer == 2){
echo "<ul>";
}elseif($layer == -2){
echo "</ul>";
}else{
echo "</li>";
};
};
fclose($nav);
?>
</ul>
</div>
<?
};
?>
So, again it's not shown here, but I'm trying to add a third "layer" but it isn't nested within this .
If you want the navigation outside a mess of code you could use something like the following. This would allow for layering but still simple codeing. And I think a lot easier to understand when you check this code back in a year or so then using -2
and 2
menu.php
<?php
function AddMenuItem($url, $name)
{
$active_page = basename($_SERVER['PHP_SELF']);
if ($active_page == $url)
echo "<div class='active'>".$name."</div>";
else
echo "<a href='".$url."'>".$name."</a>";
}
?>
<ul>
<li>
<?php echo AddMenuItem("index.php", "Home"); ?>
</li>
<li>
<?php echo AddMenuItem("products.php", "Products"); ?>
<ul>
<li>
<?php echo AddMenuItem("ace.php", "Ace Blade"); ?>
</li>
<li>
<?php echo AddMenuItem("electrodes.php", "Electrodes"); ?>
</li>
<li>
<?php echo AddMenuItem("megasoft.php", "Mega Soft"); ?>
</li>
</ul>
</li>
<li>
<?php echo AddMenuItem("samples.php", "Samples"); ?>
</li>
</ul>
index.php, products.php, ace.php, etc.
<?php require_once("menu.php"); ?>