Jump to content

Handling special cases: The elusive navigation menu override


MoritzLost
 Share

Recommended Posts

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!

  • Like 18
  • Thanks 4
Link to comment
Share on other sites

Some great musing there!

I don't think there will ever be a one-size-fits-all approach for creating menus that works for every site. Sometimes I match the menu exactly to the page tree. Sometimes I hard code it. Sometimes I have a checkbox field that determines if each page should be in the menu. Sometimes I let the site editors control it like this with two page reference fields for the header and footer menu respectively, and put it in a "Menus" tab on the homepage. And sometimes it's a combination of these approaches for different parts of the site.

There are so many options and each has its place.

image.thumb.png.4d0883d01cee9f8536ebf9710781bcb5.png

  • Like 8
Link to comment
Share on other sites

Hi @MoritzLost,

great Tutorial again! :)

I'm short in time but can give an example for a custom solution that I use sometimes. It suites for small sites or landingpages where the clients have the need to also include external links into the main menu.

 

custom-menu.thumb.gif.d69b58cae6f8cafd2f00585d9f102c1f.gif

 

PS: .. and yes, I try to avoid those things and instead try to stick with the native page tree hirarchy, as it is less error prone for the customers as with an additional layer involved.

 

  • Like 5
  • Thanks 1
Link to comment
Share on other sites

I also use different ways for implementing menus, depending on what I find appropriate. Here is a repeater based, one level customizable menu, where hiding fields on conditions makes it possible to switch between "custom" and page picker options:

menu_item-repeaters.thumb.gif.996fa4b3b23c8e2d1df02c4c28d595b6.gif

  • Like 8
Link to comment
Share on other sites

@adrian @horst @szabesz Thanks! Interesting how those solutions are different yet similar. I usually do something like this for footer menus that tend to be more custom, since it only contains a cherry-picked selection of the most important pages. I have tried a couple different combinations of fields, with different levels of control. Since we're doing screenshots, here's the latest iteration that I find quite flexible:

13082688_Screenshot2019-09-04at11_48_41.thumb.png.ce7e642c16254f33adf2b697714ee8ae.png

Sorry it's in German. Basically, there's a repeater "Footer regions", each containing a headline and a repeater with links. The regions get displayed as individual columns in the footer. Each link has a radio selection between "Internal page", "External URL" and "Download", and a "Link-Text" field. Depending on the radio selection, the respective field get displayed (page reference, URL or file Upload). If the Link-Text is empty, the link is displayed with a reasonable default (Page title for internal pages, domain for external URLs, file basename for files). I initially disliked having too use an additional field for the link-type, but it provides better usability for the client in my experience.

@horst I like the solution with the show_only_if fields, though it might not be clear to clients how to switch it back? I found that the interaction with fields being only visible when other fields are empty/filled is not so intuitive for clients.

@szabesz Interesting, is the "Open blank" option something your clients actively use? I usually just handle that in the template, i.e. all URLs to different hosts get target="_blank" rel="noopener" automatically ...

  • Like 4
Link to comment
Share on other sites

2 hours ago, MoritzLost said:

@horst I like the solution with the show_only_if fields, though it might not be clear to clients how to switch it back? I found that the interaction with fields being only visible when other fields are empty/filled is not so intuitive for clients.

Yes, especially in my example its not obvious. But all sites where I used that belong to the same agency. And only agency members maintain those pages, not the clients.

With other solutions, where I use the show_only_if functionality, I always only use it with checkboxes or radios as toggle controls, where the toggle controls always stay visible.

 

2 hours ago, MoritzLost said:

@szabesz Interesting, is the "Open blank" option something your clients actively use? I usually just handle that in the template, i.e. all URLs to different hosts get target="_blank" rel="noopener" automatically ...

I also do it the same in the template. I don't give it as choice for the editors.

  • Like 4
Link to comment
Share on other sites

14 hours ago, MoritzLost said:

Interesting, is the "Open blank" option something your clients actively use? I usually just handle that in the template, i.e. all URLs to different hosts get target="_blank" rel="noopener" automatically ...

It was not that much necessary for sure, I put it there because the actual external link points to a partner institution and they might change their mind regrading "to be blank, or not to be blank, that is the question :)". Sure, I could change it for them should they ever change their mind, but I also wanted PW look professional as this is the first time they see/use it and the editor of the site is a former programmer... Motivations vary too, not just requirements ? 

  • Like 4
Link to comment
Share on other sites

I know I am getting OT, but I almost never use target="_blank" anymore.

Here are a few thoughts: https://css-tricks.com/use-target_blank/

I think the key thing for me is that it's really hard to prevent opening a new tab when it is used, but it's really easy for the user to choose to open in a new tab if they want, so my rule is that unless the user will lose unsaved form data as a result of opening a link in the same tab, I never force a new tab.

 

  • Like 4
  • Thanks 1
Link to comment
Share on other sites

7 minutes ago, adrian said:

Hmm, I'm not convinced that just because something used to be artificially defined as standard that means it is necessarily "ideal". I've seen so many people not knowing that the browser has a back button/feature (let alone the history...), getting confused by navigating away from the site, using Google just to find it again. But these individuals in question are aware of the tabs feature of the browser – and they do use it – as tabs are promptly visible (at least on desktop) and such users only use what they see right in front of them. Menus and shortcuts? Alien to them.

The article is certainly subjective yet tries to look objective. The article's points certainly have merits, but just as our main topic, I think requirements vary and so do implementations based on that...

  • Like 5
Link to comment
Share on other sites

6 hours ago, szabesz said:

It was not that much necessary for sure, I put it there because the actual external link points to a partner institution and they might change their mind regrading "to be blank, or not to be blank, that is the question :)". Sure, I could change it for them should they ever change their mind, but I also wanted PW look professional as this is the first time they see/use it and the editor of the site is a former programmer... Motivations vary too, not just requirements ? 

@szabesz Fair enough! ?

@adrian As a user, I agree - i don't like it when I try to navigate away from a page using a link, and it opens in a new page, forcing me to go back to close the tab. But we're power users, I'm not sure everyone knows how to open links in a new tab (especially on mobile, not everyone gets the long-press interaction!). As for why I still use target blank basically for all external links, you know, business reasons. Almost every client sees red when they encounter a link that leads them away from their site. Not sure why everyone expects their audience to have the attention span of a mouse, but oh well ... it's not something I want to spend energy discussing every time. I can see both sides though.

  • Like 3
Link to comment
Share on other sites

  • 2 weeks later...
On 9/5/2019 at 8:31 AM, MoritzLost said:

@szabesz Fair enough! ?

@adrian As a user, I agree - i don't like it when I try to navigate away from a page using a link, and it opens in a new page, forcing me to go back to close the tab. But we're power users, I'm not sure everyone knows how to open links in a new tab (especially on mobile, not everyone gets the long-press interaction!). As for why I still use target blank basically for all external links, you know, business reasons. Almost every client sees red when they encounter a link that leads them away from their site. Not sure why everyone expects their audience to have the attention span of a mouse, but oh well ... it's not something I want to spend energy discussing every time. I can see both sides though.

I've encountered users who don't even know what a tab is, and are confused when they cannot get back to the site they were on before by just hitting the back button! It's no use keeping your site up in the background if your users don't know how to get back to it ?  So on principle I agree with @adrian on this, but our clients still keep asking for target="_blank", so that's that.

  • Like 4
Link to comment
Share on other sites

I may have missed some of the points made here (sorry in advance), but regarding links opening in new tab/window: please keep in mind that this is a problem from accessibility point of view.

For typical desktop users with decent eye sight etc. this is usually not a problem – and in fact it may be nice in some cases that a link automatically opens in a new tab – but for most screen readers (apps, that is – and thus their users as well) it's a real problem. From what I've heard/read, it can entirely mess up their understanding of the context.

WCAG advises that if you're about to open a link in a new window, you should provide a clear signal that this is going to happen. This can, for an example, be a note at the end of the link text: "(opens in a new window)".

Quote

Opening new windows automatically when a link is activated can be disorienting for people who have difficulty perceiving visual content, and for some people with cognitive disabilities, if they are not warned in advance. Providing a warning allows the user to decide it they want to leave the current window, and the warning will help them find their way back, if they do decide they would like to go to the new window. It will help them understand that the "back" button will not work and that they have to return to the last window they had open, in order to find their previous location.

If you care about accessibility, think twice before you use target="_blank". And for those cases where the client requests this, be sure to inform them that it will likely cause issues for some users. If the client still wants to go with it then by all means do it, but I've found this argument to resonate quite well with most sensible people ?

  • Like 5
Link to comment
Share on other sites

@teppo's argument here is solid and I thought... cool... just add some details to those links with CSS-magic:

a[target=_blank]:after {
	content: " (opens in a new window)";
}

BUT... not all screenreaders support that feature... all I found was kind of a mixed result.

https://www.powermapper.com/tests/screen-readers/content/css-generated-content/

Just in case for those who had a similar idea. ?

  • Like 4
Link to comment
Share on other sites

13 hours ago, wbmnfktr said:

BUT... not all screenreaders support that feature... all I found was kind of a mixed result.

https://www.powermapper.com/tests/screen-readers/content/css-generated-content/

So true. It's a nice idea, but CSS content is indeed problematic.

Sometimes you want to add otherwise meaningless (visual) content (like icons) with CSS content and it turns out that some screen readers read them out loud, which can be quite confusing. There's no aria-hidden for CSS content, so reliably hiding said content from screen readers can be a real hassle. On the other hand there are times when you actually want to provide content for screen readers with this technique – yet it turns out that some of them will happily disregard it.

In my experience it's almost never a good idea to add content with CSS ?

  • Like 2
Link to comment
Share on other sites

@teppo @wbmnfktr Wow this discussion derailed a bit, but here we are ^^ Teppo, thanks for the pointers regarding target blank, I didn't really have that on my radar. Makes perfect sense though, I'll definitely reconsider my current approach! Even more off-topic, but I feel a bit smug now about having isolated that logic into a twig template in my current project, so now I can change it in a central place:

{# blocks/link-start.twig #}

{#-
 # Renders a start tag for a link. The link will automatically have target="_blank"
 # and rel="noopener" if the link leads to an external domain.
 #
 # @var string url          The target (href) for the URL.
 # @var bool is_download    Should the link be marked as a download (for direct file downloads)?
 # @var array classes       Optional classes for the anchor.
 -#}

<a href="{{ url }}"
    {%- if is_download is defined and is_download %} download{% endif -%}
    {%- if classes is defined and classes is not empty %} class="{{ classes|join(' ')|trim }}"{% endif -%}
    {%- if isExternalUrl(url) %} target="_blank" rel="noopener"{% endif %}>

I'll just get rid of the last part ?

Thanks to everyone participating in the discussion! I think it's great how different perspectives come together that provide everyone new insights & best practices ...

  • Like 4
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

×
×
  • Create New...