Build a context provider for active Drupal menus
Building a custom Drupal Context provider for active menu items gives site teams a reusable way to treat current navigation state as a condition. Drupal already applies active and parent classes when rendering a menu, but those classes are presentation details. A provider turns the matching link into server-side context that can drive blocks, layouts, Views or editorial behaviour without brittle path checks.
The pattern suits sites where navigation state determines more than a colour change. It also gives Australian Drupal teams one rule across separate builds: the same menu link should activate the same block in Sydney, Melbourne and a regional council’s Canberra office, regardless of local path aliases. That consistency matters when public-sector, education and membership organisations maintain Drupal estates with different hosting and review routines.
Why navigation state belongs in Context
Drupal’s Context module evaluates conditions and reactions for the current request. A provider contributes values such as the active link, while a condition decides whether a context applies and reactions act on that result. Separating those jobs keeps matching logic out of theme preprocess functions and avoids repeating path assumptions in every site.
Menu rendering can already identify current ancestors, so a provider is not needed merely to add an active class. It is valuable when one rule must be shared between display, content workflows or custom services. For example, a “Local publications” section might show a sidebar only on items beneath a Publications menu entry.
The design should answer one precise question: which configured menu link represents this route? The answer can then be reused by a context condition, a service or a preprocess function. That explicit definition suits the informal “have a go” style common in Australian workplace conversations while preserving the repeatable release notes needed when agencies hand work to internal teams.
Designing the provider and its values
Start with a custom module such as active_menu_context and declare a dependency on drupal:context. Keep route matching and menu loading in a resolver service. The provider should only translate that service’s result into Context values, making the matching behaviour easier to test in isolation.
<?php
namespace Drupal\active_menu_context\Plugin\ContextProvider;
use Drupal\active_menu_context\Service\ActiveMenuResolver;
use Drupal\context\ContextProviderBase;
use Drupal\Core\Plugin\Context\ContextValue;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* @ContextProvider(
* id = "active_menu_item",
* label = @Translation("Active menu item"),
* description = @Translation("Exposes active menu links for the current route."),
* )
*/
final class ActiveMenuProvider extends ContextProviderBase {
public function __construct(private ActiveMenuResolver $resolver) {}
public static function create(ContainerInterface $container): self {
return new static($container->get('active_menu_context.resolver'));
}
public function getContextValues(): array {
$state = $this->resolver->resolve();
return [
'active_menu_item' => new ContextValue('active_menu_item', $state['id']),
'active_menu_items' => new ContextValue('active_menu_items', $state['ids']),
'active_menu_trail' => new ContextValue('active_menu_trail', $state['ancestors']),
];
}
public function getContextValue($context_id) {
$state = $this->resolver->resolve();
if ($context_id === 'active_menu_item') {
return $state['id'];
}
if ($context_id === 'active_menu_items') {
return $state['ids'];
}
if ($context_id === 'active_menu_trail') {
return $state['ancestors'];
}
return NULL;
}
}
Register the resolver as active_menu_context.resolver and inject the current route match plus Drupal’s menu-link tree service. Configure the resolver with the menu names it should inspect, such as main and footer, rather than loading every registered menu. It should also memoise its result for the current request because Context evaluation can happen several times during rendering.
A scalar active_menu_item value gives an editor a straightforward value for an equality condition. The two array values provide richer data for custom code: every matching link and the ordered ancestor chain. To select a particular link in the Context interface, add a companion Context condition plugin that reads active_menu_item and offers a dropdown of eligible plugin IDs.
Matching routes to menu links
Load candidate links from each configured menu and flatten the tree to the required depth. Compare each candidate URL with the current route match, using its internal route name and route parameters. This avoids comparing aliases as plain strings and keeps the behaviour intact when an editor changes a path alias.
The central comparison can remain small:
private function matches(Url $candidate, RouteMatchInterface $match): bool {
$route = $candidate->getRouteName();
if ($route === NULL || $route !== $match->getRouteName()) {
return FALSE;
}
$current = $match->getRawParameters();
foreach ($candidate->getRouteParameters() as $name => $value) {
if (!array_key_exists($name, $current)
|| (string) $current[$name] !== (string) $value) {
return FALSE;
}
}
return TRUE;
}
Query strings normally should not affect the active state, while external links have no internal route and can be skipped. Drupal represents the site’s front-page link through the system.site route, so it can follow the same rules as other candidates. If a menu points to a View route, decide whether its complete parameter set or only a defined subset must match; otherwise several Views pages may appear to activate the same item.
Several links can legitimately share a route. Return all of them in active_menu_items, then choose a deterministic primary value for active_menu_item using the configured menu order. Build active_menu_trail from the menu tree’s parent metadata, preserving the path from the immediate parent to the root. Access checks, translated links and unpublished menu items still need their normal Drupal handling.
Applying context to menus and editorial workflows
Create a context at /admin/structure/context, add the custom active-menu condition and select the relevant menu link. A reaction can then control a block, layout region or other Context-aware element. For instance, a supporting-resources block can appear only beneath the current service family, while editors use the same route decision to identify content affected by a navigation restructure.
Editorial teams can pair that display rule with the Workbench moderation checklist to decide which pages require review before publication. This is particularly useful for Australian council and government sites, where service information may be maintained by several teams and published in stages.
Keep provider work lightweight. Context evaluation can occur during block rendering, access checks and preprocess functions, so loading the same menu repeatedly is wasteful. The resolver should retain data for the request only, and page caches must vary by the relevant route or context. Avoid caching unpublished paths as shared pages, particularly where a cached block could reveal content that the current visitor should not see.
Deployment safeguards and recommendations
Deployment should begin with kernel tests that combine route-match and menu-link fixtures. Cover a normal content route, an aliased path, the front page, a link with query parameters, a missing route and duplicate links sharing the same route. Browser tests should confirm that the context condition, reaction and visible menu state remain aligned. Australian public-sector Drupal work also requires accessible keyboard operation and a visible focus or state beyond colour alone.
Three approaches can supply the same navigation decision with different long-term costs:
| Approach | Handles aliases | Provides parent trail | Integrates with Context | Maintenance |
|---|---|---|---|---|
| Core menu link classes | Yes | Yes | Available to themes and CSS | Low |
| Custom Context provider | Yes, through route metadata | Yes, when exposed | Available to conditions and services | Medium |
| Raw path comparison | Only after alias resolution | No by default | Possible but brittle | Medium to high |
The provider should log the menu name, link plugin ID, route name and UTC timestamp while avoiding raw query strings. Many Australian organisations covered by the Privacy Act 1988 treat logged URLs as potentially containing personal information, even when the menu state itself is harmless. Retention and access controls for those logs should follow the organisation’s usual privacy practices.
- Restrict the resolver to explicitly configured menus and retain menu order when choosing a primary match.
- Compare internal routes and parameters instead of aliases or translated path strings.
- Expose plugin IDs and ancestors separately, then memoise resolution for the request.
- Automate tests for aliases, the front page, duplicate routes, permissions and unpublished links.
With a defined matching contract and tested context values, the provider becomes a small, dependable bridge between Drupal’s menu system and Context-based behaviour across development, editorial and production environments.