Jump to content
Macrura

Custom Menu (not related to page tree)

Recommended Posts

Recently I've been working on a site where it seemed like it was going to be impossible to keep the page tree and the needs of the site's main menu in harmony;

So to solve this I setup a separate page tree under a hidden page called 'Main Menu', with each menu item having three fields: title, menu-link-page, and menu-link-url. All of the menu items are also hidden, so the code below uses the include=all parameter when getting the pages for the tree.

To generate the main menu markup, i adapted the great code that was developed by Soma for Joss's bootstrap menu, and modified it to output links to the menu-link-page or menu-link-url; (Entering a value in the menu-link-url field overrides any selection in the menu-link-page.)

This solution has enabled me to setup the menu exactly how the site needs it, even if the menu heirarchy is not the same as the page heirarchy, and has solved a lot of problems and made things easier for this scenario. For example, menu items can easily contain external URLs, to subdomain pages, or other related site's pages. (In this case the client has a separate web store for selling parts). Also, all of the parent menu items had to use a javascript:void() as the href, in order for the accordion version to work right on mobile; So this was easy to do by putting that into the menu-item-link field.

In the code below, page #1271 contains the menu tree, so it is specified as a parameter to the $root variable.

I think this sort of setup, using a custom menu tree, could solve a lot of the questions I've seen recently on the forum; I probably wouldn't use this technique on small sites since it is more work, but for larger ones where you might need a lot of menus, this could be helpful.  Also, if you had to setup a Mega Menu, with images and icons, this might make it easier to manage.

<?php

/**
 *  render custom markup menu for bootstrap nested navigation
 *
 * @param  PageArray  $pa     pages of the top level items
 * @param  Page  $root   root page optional, if you use other root than home page (id:1)
 * @param  string  $output for returned string collection
 * @param  integer $level  internally used to count levels
 * @return string          menu html string
 */
function renderChildrenOf($pa, $root = null, $output = '', $level = 0) {
    if(!$root) $root = wire("pages")->get(1);
    $output = '';
    $level++;
    foreach($pa as $child) {
        $class = '';
        $has_children = count($child->children('include=all')) ? true : false;

        if($has_children && $child !== $root) {
            if($level == 1){
                $class .= 'parent'; // first level boostrap dropdown li class
                //$atoggle .= ' class="dropdown-toggle" data-toggle="dropdown"'; // first level anchor attributes
            }
        }

        // make the current page and only its first level parent have an active class
        if($child->menu_item_page === wire("page")){
            $class .= ' active';
        } else if($level == 1 && $child !== $root){
            if($child->menu_item_page === wire("page")->rootParent || wire("page")->parents->has($child)){
                $class .= ' active';
            }
        }

        $class = strlen($class) ? " class='".trim($class)."'" : '';
        if($child->menu_item_url) {$childlink = $child->menu_item_url; } else { $childlink = $child->menu_item_page->url; }
        $output .= "<li$class><a href='$childlink'>$child->title</a>";

        // If this child is itself a parent and not the root page, then render its children in their own menu too...
        if($has_children && $child !== $root) {
            $output .= renderChildrenOf($child->children('include=all'), $root, $output, $level);
        }
        $output .= '</li>';
    }
    $outerclass = ($level == 1) ? "accordmobile" : '';
    return "<ul class='$outerclass'>$output</ul>";
}

// bundle up the first level pages and prepend the root home page
// $root = $pages->get(1);
// $pa = $root->children;
// $pa = $pa->prepend($root);

// Set the ball rolling...
// echo renderChildrenOf($pa);

// example with pages further down in the tree

$root = $pages->get("1271");
$pa = $root->children('include=all');
// $pa = $pa->prepend($root);

// add the root as the second parameter
echo renderChildrenOf($pa,$root);
 
  • Like 3

Share this post


Link to post
Share on other sites

I think it's a fine way to go when there is no way to make the site structure consistent with the navigation, for certain parts (like top navigation or footer nav, etc.) Still I think it's always preferable to keep a consistent site and navigation structure whenever possible. A layer of pages separate from the structure, just for menus, is [in most cases] and unnecessary bit of complexity. But for those times when you will benefit from it, it's a nice pattern to have. 

Share this post


Link to post
Share on other sites

Hey Ryan - thanks for replying to this.

RIght... i think in most cases using the PW tree to generate the menu is best; But it does speak to the flexibility of PW that you can do something like this with relative ease when required...and in setting this up I learned from Soma's bootstrap menu markup how to generate complex nav markup without using a plugin..

I have heard it said somewhere that the navigation menu should be optimized for the user and not be constrained by the hidden structure of the site, especially for larger sites. In this case, it is a company where many of the products overlap in functionality, so there needs to be several routes for different users to arrive at certain pages.  And they are not extremely organized yet about the content, so i'm sort of dumping all of the content into the tree in what seems like a logical structure, and then linking to things as necessary, with the custom menu.  It's also helping to prevent confusion in some cases for links to external sites, where those would have been showing in the page tree if we did it that way.

This site will also have a lot of advanced search and filter types of things, so the nav is kind of secondary to that route for finding pages...

-marc
 

  • Like 2

Share this post


Link to post
Share on other sites
I have heard it said somewhere that the navigation menu should be optimized for the user and not be constrained by the hidden structure of the site, especially for larger sites.

True, if you don't have control over the structure. In my experience, what's good for the user, and good for the structure, are closely tied together. And it tends to hold true regardless of scale. So I try to base my structure around what's good for the user, and that usually ends up being ideal for everything else. I'm sure there are exceptions though.

In this case, it is a company where many of the products overlap in functionality, so there needs to be several routes for different users to arrive at certain pages.  And they are not extremely organized yet about the content, so i'm sort of dumping all of the content into the tree in what seems like a logical structure, and then linking to things as necessary, with the custom menu. 

I think this is okay so long as you don't run into a situation where the same rendered page is being delivered at multiple URLs. 

If you are dealing with lots of products with multiple classifications, a good approach is to throw them all in a bucket (i.e. /products/) and then relate with categories via page relations. In this manner, you aren't maintaining a separate menu, but building upon existing page relations. 

It's also helping to prevent confusion in some cases for links to external sites, where those would have been showing in the page tree if we did it that way.

I usually have a template called 'redirect' that has nothing but a title and URL field. It's good for handling external links, or even occasional internal links as navigation placeholders. Like you mentioned, this puts it in your page tree. Usually that's what I want, but I tend to only have the need for the 'redirect' template occasionally.

This site will also have a lot of advanced search and filter types of things, so the nav is kind of secondary to that route for finding pages...

With the unknowns in terms of structure that you are dealing with, I think the approach you are taking with separate menu makes sense. It probably also makes sense in this case to go with a more bucket-oriented structure for the content (like the /products/ you mentioned). 

  • Like 2

Share this post


Link to post
Share on other sites

Thanks Ryan -

I think i will use the redirect template idea for some things..Right now there are no multiple URLs, everything is well organized in the page tree, diescrreet

now you're giving me some ideas about how to improve this – right now the products are arranged heirarchially under one parent, and then 4 'categories' with all of the products under each of those; But now i'm thinking that ALL of the products should have the same parent, i think this will make it more flexible to show search results.. then i guess i'll use URL segments for the product category, application, name etc...if i do it this way, there will be multiple URLs to the same page, but i could then use canonical URLs;

  • Like 1

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MoritzLost
      In this tutorial I want to write about handling special cases and change requests by clients gracefully without introducing code bloat or degrading code quality and maintainability. I'll use a site's navigation menu as an example, as it's relatable and pretty much every site has one. I'll give some examples of real situations and change requests I encountered during projects, and describe multiple approaches to handling them. However, this post is also about the general mindset I find useful for ProcessWire development, which is more about how to handle special cases and still keep your code clean by making the special case a normal one.
      The problem: Special cases everywhere
      Since ProcessWire has a hierarchical page tree by default, as a developer you'll usually write a function or loop that iterates over all children of the homepage and displays a list of titles with links. If the site is a bit more complex, maybe you additionally loop over all grandchildren and display those in drop-down menus as well, or you even use a recursive function to iterate over an arbitrary amount of nested child pages. Something like this:
      function buildRecursiveMenu(Page $root): string { $markup = ['<ul class="navigation">']; foreach ($root->children() as $child) { $link = '<a class="navigation__link" href="' . $child->url() . '">' . $child->title . '</a>'; $children = $child->hasChildren() ? buildRecursiveMenu($child) : ''; $markup[] = "<li class="navigation__item">{$link}{$children}</li>"; } $markup[] = '</ul>'; return implode(PHP_EOL, $markup); } But then the requests for special cases come rolling in. For example, those are some of the requests I've gotten from clients on my projects (by the way, I'm not saying the clients were wrong or unreasonable in any of those cases - it's simply something I needed to handle in a sensible way):
      The homepage has the company's name as it's title, but the menu link in the navigation should just say "Home". The first page in a drop-down menu should be the top-level page containing the drop-down menu. This was requested because the first click on the top-level item opens the sub-navigation instead of navigating to that page (espcially on touch devices, such as iPads, where you don't have a hover state!), so some visitors might not realize it's a page itself. Some top-level pages should be displayed in a drop-down menu of another top-level page, but the position in the page tree can't change because of the template family settings. The menu needs to contain some special links to external URLs. For one especially long drop-down menu, the items should be sorted into categories with subheadings based on a taxonomy field. In general, my solutions to those requests fall into three categories, which I'll try to elaborate on, including their respective benefits and downsides:
      Checking for the special case / condition in the code and changing the output accordingly (usually with hard-coded values). Separating the navigation menu from the page tree completely and building a custom solution. Utilizing the Content Management Framework by adding fields, templates and pages that represent special states or settings. Handling it in the code
      This is the simplest solution, and often the first thing that comes to mind. For example, the first request (listing the homepage as "Home" instead of it's title in the navigation) can be solved by simply checking the template or ID of the current page inside the menu builder function, and changing the output accordingly:
      // ... $title = $child->template->name === 'home' ? 'Home' : $child->title; $link = '<a class="navigation__link" href="' . $child->url() . '">' . $title . '</a>'; // ... This is definitely the fastest solution. However, there are multiple downsides. Most notably, it's harder to maintain, as each of those special cases increases the complexity of the menu builder function, and makes it harder to change. As you add more special conditions, it becomes exponentially harder to keep changing it. This is the breeding ground for bugs. And it's much harder to read, so it takes longer for another developer to pick up where you left (or, as is often cited, for yourself in six months). Also, now we have a hard-coded value inside the template, that only someone with access to and knowledge of the template files can change. If the client want's the link to say "Homepage" instead of "Home" at some point, they won't be able to change it without the developer. Also, each special case that is hidden in the code makes it harder for the client to understand what's going on in terms of template logic - thus increasing your workload in editorial support.
      That said, there are definitely some times where I would go with this approach. Specifically:
      For smaller projects that you know won't need to scale or be maintained long-term. If you are the only developer, and/or only developers will edit the site, with no "non-technical" folk involved. For rapid prototyping ("We'll change it later") Building a custom solution
      My initial assumption was that the main navigation is generated based on the page tree inside ProcessWire. But of course this isn't set in stone. You can just as easily forgo using the page tree hierarchy at all, and instead build a custom menu system. For example, you could add a nested repeater where you can add pages or links on a general settings page, and generate the menu based on that. There are also modules for this approach, such as the Menu Builder by @kongondo. This approach is not the quickest, but gives the most power to the editors of your site. They have full control over which pages to show and where. However, with great power comes great responsibility, as now each change to the menu must be performed manually. For example, when a new page is added, it won't be visible in the menu automatically. This is very likely to create a disconnect between the page tree and the menu (which may be what you want, after all). You may get ghost pages that are not accessible from the homepage at all, or the client may forgot to unpublish pages they don't want to have any more after they've removed them from the menu.
      I would only go with this approach if there are so many special cases that there hardly is a "normal case". However, even then it might not be the best solution. The direct relationship between the page tree, the menu structure and page paths are one of the strongest features of ProcessWire in my opinion. If many pages need to be placed in special locations without much structure in regards to what templates go where, maybe you only need to loosen up the template family settings. I have built one site without any template family restrictions at all - any page of any template can go anywhere. It's definitely a different mindset, but in this case it worked well, because it allowed the client to build custom sections with different page types grouped together.
      It's a trade-off, as it is so often, between flexibility and workload. Weigh those options carefully before you choose this solution!
      Utilizing the CMF
      This is the middle ground between the two options above. Instead of building a completely custom solution, you keep with the basic idea of generating a hierarchical menu based on the page tree, but add fields and templates that allow the editor to adjust how and where individual pages are displayed, or to add custom content to the menu. of course, you will still write some additional code, but instead of having hard-coded values or conditions in the template, you expose those to the client, thereby making the special case one of the normal cases. The resulting code is often more resilient to changing requirements, as it can not one handle that specific case that the client requested, but also every future change request of the same type. The key is to add fields that enable the client to overwrite the default behaviour, while still having sensible defaults that don't require special attention from the editor in most cases. I'll give some more examples for this one, as I think it's usually the best option.
      Example 1: Menu display options
      This is probably the first thing you thought of for the very first change request I mentioned (displaying the homepage with a different title). Instead of hard-coding the title "Home" in the template, you add a field menu_title that will overwrite the normal title, if set. This is definitely cleaner than the hard-coded value, since it allows the client to overwrite the title of any page in the menu.
      I'll only say this much in terms of downsides: Maybe the menu title isn't really what the client wanted - instead, perhaps they feel limited because the title is also displayed as the headline (h1) of the page. In this case, the sensible solution would be an additional headline field that will overwrite the h1, instead of the menu_title field. Which fields are really needed is an important consideration, because you don't want to end up with too many. If each page has fields for the title, a headline, a menu title and an SEO-title, it's much more complicated than it needs to be, and you will have a hard time explaining to the client what each field is used for.
      Another example in this category would be an option to "Hide this page in the menu". This could be accomplished by hiding the page using the inbuilt "hidden" status as well, but if it's hidden it won't show up in other listings as well, so separating the menu display from the hidden status might be a good idea if your site has lots of page listings.
      Example 2: "Menu link" template
      One solution that is quite flexible in allowing for custom links to pages or external URLs is creating a menu-link template that can be placed anywhere in the page tree. This templates can have fields for the menu title, target page and/or external target URL. This way, you can link to another top-level page or an external service inside a drop-down menu, by placing a Menu Link page at the appropriate position. This is also a clean solution, because the navigation menu will still reflect the page tree, making the custom links visible and easily editable by the editors.
      A minor downside is that those templates are non-semantical in the sense that they aren't pages with content of their own. You'll need to make sure not to display them in listings or in other places, as they aren't viewable. It may also require loosening up strict family rules - for example, allowing for Menu Link pages to be placed below the news index page, which normally can only hold news pages.
      Example 3: Drop-down menu override
      This one is a more radical solution to override drop-down menus. You add a repeater field to top-level pages, similar to the one mentioned as a custom solution, where you can add multiple links to internal pages or URLs. If the repeater is empty, the drop-down menu is generated normally, based on the sub-pages in the page tree. But if the repeater contains some links, it completely overrides the drop-down menu. It's similar to the fully custom solution in that as soon as you override a sub-menu for a top-level page, you have to manually manage it in case the page structure changes. But you can make that decision for each top-level page individually, so you can leave some of them as is and only have to worry about the ones that you have overwritten.
      Again, this offers sensible defaults with good customizability. A downside is that the mixed approach may confuse the client, if some changes to the page tree are reflected in the drop-down menu directly, while others don't seem to have any effect (especially if you have multiple editors working on a site).
      Finding the right solution
      So how do you choose between the approaches? It depends on the client, the requirements, and on what special cases you expect and want to handle. Sometimes, a special request can be turned down by explaining how it would complicate editorial workflows or have a negative impact on SEO (for example, if you risk having some pages not accessible from the homepage at all). Also, make sure you understand the actual reason behind a change request, instead of just blindly implementing the suggestion by the client. Often, clients will suggest solutions without telling you what the actual problem is they're trying to solve.
      For example: In one case, I implemented the drop-down override mentioned in example three. However, what the client really wanted was to have the top-level page as the first item in the drop-down menu (see the example requests mentioned above). So they ended up overwriting every single drop-down menu, making the menu harder to maintain. In this case, it would have been better to go with a more specialized solution, such as adding a checkbox option, or even handling it in the code, since it would have been consistent throughout the menu.
      Another example was mentioned above: If the client requests an additional "Menu title" field, maybe what they really need is a "Headline" field. I recommend reading Articulating Design Decisions by Tom Greever; it includes some chapters on listening to the client, finding out the real reason behind a change request, and responding appropriately. It's written from a design perspective, but is applicable to development as well, and since UX becomes more important by the day, the lines between the disciplines are blurred anyway.
      Conclusion
      I realize now this reads more like a podcast (or worse, a rant) than an actual tutorial, but hopefully I got my point across. ProcessWire is at is greatest if you utilize it as a Content Management Framework, creating options and interfaces that allow for customizability while retaining usability for the client / editor. I usually try to hit a sweet spot where the editors have maximum control over the relevant aspects of their site, while requiring minimal work on their part by providing sensible defaults. Above, I listed some examples of requests I've gotten and different solutions I came up with to handle those with custom fields or templates. Though in some cases the requirements call for a custom solution or a quick hack in the template code as well!
      What are some of the special requests you got? How did you solve them? I'd love to get some insights and examples from you. Thanks for reading!
    • By wiredny
      I want to remove the "Home" page from the navbar, but keep the other pages (About, Templates, etc) on the navbar? How is this done?
       
       
    • By kaba86
      Hello PW Community, really glad that discovered this CMS recently, it is very strange it took so long That idea of no front design limitations is just awesome!
      Need to say that I have a bit of knowledge of html and css, but almost no php, so I need your help.
      What I want to do is an article posting  cms, with this structure:
       
      - Homepage - Projects - Articles -- Category 1 --- Articles of category 1 -- Category 2 --- Articles of category 2 - About - Contact Found this ProcessWire Profile https://github.com/tutsplus/how-to-create-an-ajax-driven-theme-for-processwire
      It covers almost all my needs, except the menu. When I add a childpage for this page http://artist.nicegrp.com/publications/world-world/ , World:World doesn't appear under Writings & Publications.
      I need a menu that works like a breadcrumb, that shows on the menu the category that you are viewing. So when I'm in articles page, on the menu it shows only articles and it's categories. When I get into a category, that category takes state active link but doesn't show on the menu links and titles for contained articles. How can I do that?
      Sorry for my long writing and English, it is not my native but I hope you understood what I need. Can you help me with that?
      Thank you
       
    • By rareyush
      hi everyone
       
      I am trying get a full width sub-menu on 3rd item in menu or navbar which is coming from a loop.
      i was hoping this can be done by using jquery by targeting 3rd element in navbar but jquery is blocked in some browser by default so is there any other method I can do this
    • By darrenc
      I'm trying to understand how I could have users log in as "members", provide them with a customized experience, but still serve them cached pages?
      For example let's say I have 3 roles
      Guest Member SuperUser And let's say I have a NavBar type component that has a menu. Plus it has "log in!" if guest,  or "logged in as Mike Smith"
      I would want guests to see a cached site with guest-only page access. Members should also see cached pages, but their menu may have access to members-only pages or fields or information. Furthermore they might have a "logged in as Mike Smith" element. SuperUsers can stay uncached. How does one go about creating that cache so that visitors aren't constantly re-creating the menu? Or that when "Sally Baker" logs in, she doesn't see a homepage that is cached for "Mike Smith" with all his elements?
      Thank you in advance for any replies. 
       
       
×
×
  • Create New...