Skip to content

Menu Link Attributes

Menu Link Attributes adds HTML attributes to menu links created through the menu UI. Site builders define the available attributes once in YAML, and editors fill them in on the menu link form. Attributes go on the link (<a>) or on the wrapping list item (<li>).

Features

  • Define any number of attributes (class, target, rel, data-*, aria-*, and so on) in a YAML configuration form.
  • Give each attribute a label, description, default value, and form element type: text field, select list, radios, or checkboxes.
  • Apply attributes to the <li> container instead of the <a> element.
  • Separate permissions for defining attributes and for filling them in.
  • Attribute values are added to all translations of a menu link.
  • Attribute names such as style and event handlers (on*) are rejected, and values are filtered before rendering.

How it works

flowchart LR
    Config["YAML config<br>(available attributes)"] --> Form["Menu link edit form"]
    Form --> Options["Link options<br>attributes / container_attributes"]
    Options -->|core link rendering| A["&lt;a&gt; element"]
    Options -->|hook_preprocess_menu| LI["&lt;li&gt; element"]

Values are stored in the options of the menu link's link field. Link attributes end up under options.attributes, which Drupal core renders on the <a> element. Container attributes end up under options.container_attributes, which the module applies to the menu item in hook_preprocess_menu().

The attribute fields are added to the form of menu links of the menu_link_content entity type, the ones added through Structure > Menus. Links defined in a module's *.links.menu.yml file have no such form, but they get container attributes when they set them in their options:

my_module.example:
  title: 'Example'
  route_name: my_module.example
  menu_name: main
  options:
    container_attributes:
      class: ['menu-item--example']