Skip to content

USAGOV Menus module

Oscar Merida edited this page Oct 31, 2024 · 3 revisions

Problem

Tome exports placed menu blocks in the left navigation menu built from the wrong active path and the only mitigation was to export only one path per processes.

There were multiple blocks configured, depending on language and other visibility rules. Furthermore, code to customize with block was mainly in the twig templates. Twig output is cached and does not afford using Drupal APIs for getting menu items, setting cache contexts etc.

Structure

Added customs/usagov_menus module to provide the left sidebar and mobile menu blocks.

  • usagov_menus.module defines a theme function for each block.
  • src/plugin/block has a custom class per menu. They extend an AbstractMenuBlock class with common methods for querying Drupal menus, breadcrumbs.
  • templates/ holds one twig template for each. Frequently used bits of markup are wrapped in Twig macros.

Create a custom block plugin

Gotchas

Drupal's menu link manager and menu tree classes are powerful. Documentation is hard to find, best bet is to dig into existing modules for examples of how they're used.

Caching is difficult. The active link is cached per script execution, which Tome doesn't (yet) reset correctly. You need to tell Drupal if a block is unique per page/URL:

        // Ensure drupal knows this block should be cached per path.
        '#cache' => [
          'contexts' => ['url.path', 'url.query_args'],
        ]

Using the menu APIs directly bypasses pre/post process hooks.