Jump to content

How do I output my top level navigation dynamically?


ryan
 Share

Recommended Posts

Dynamic navigation is just a matter of finding the group of pages you want to output, and then loop through them to print the links. For example, if you wanted to print the top navigation:

<ul id='topnav'>
<?php 
foreach($pages->find("parent=/") as $p)
echo "<li><a href='{$p->url}'>{$p->title}</a></li>";
?>
</ul>
Link to comment
Share on other sites

  • 1 year later...

How might I modify this code to display 2 levels of navigation if it exists?

so that it would generate a <ul></ul> within an <li></li> is there were pages under it and keep it at 2 levels? I've seen a post on this on a page level and it works great on the homepage but I can't figure out how to do this on a root level consistently.

Link to comment
Share on other sites

I figured it out without a plugin, I'll post it for anyone's future reference:

<ul>
<?php

$homepage = $pages->get("/");
$mainchildren = $homepage->children;
$mainchildren->prepend($homepage);

foreach($mainchildren as $mainchild) {
 $class = $mainchild === $page->rootParent ? " class='on'" : '';
 if ($mainchild->mainNav != 0){
  echo "<li><a$class href='{$mainchild->url}'>{$mainchild->title}</a>";
  if($mainchild->path != '/' && $mainchild->numChildren > 0) {

   echo "<ul>";

   foreach($mainchild->children as $subchild) {
	$class = $page === $subchild ? " class='on'" : '';
	echo "<li><a$class href='{$subchild->url}'>{$subchild->title}</a></li>";
   }

   echo "</ul>";
  }else{
   echo "</li>";
  }

 }
}
  ?>
</ul>

For anyone wondering:

  if ($mainchild->mainNav != 0){

simply checks if a checkbox is checked that I even want it in my main menu.

  • Like 2
Link to comment
Share on other sites

Barry, using my MarkupSimpleNavigation module you could simply do:

$nav = $modules->get("MarkupSimpleNavigation");
echo $nav->render(array(
"max_levels" => 2,
"show_root" => true,
"current_class"  => "on"
));

Just in case. ;)

Edit: Ok the checkbox thing is not possible. But it would be possible using page "hidden" for page you don't want in mainnav. But your code is also nice and flexible if you need it.

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...