Drupal 8 Tip: Adding a unique class to menu links

Megan's picture

She has: 11,419 posts

Joined: Jun 1999

To add a unique class to a menu link, using the menu item's title as the class name (converting to lower case, replacing spaces with hypens):

First, create a template suggestion for your menu. Copy the menu.html.twig file from stable or classy base theme and rename to menu--yourmenu.html.twig. For the main menu, the template should be named menu--main.html.twig.

If you're using Classy as a base theme, you can modify the code that generates the classes for the menu links to add a class pulled form the menu title. This is around line 38 in the menu.html twig. Change this part:

      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

To this:

      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
          <strong>'item--' ~ item.title|clean_class,</strong>
        ]
      %}

This line takes the item title and runs it through a twig filter to create a clean class. The clean class filter converts the title to lower case and replaces strings with hyphens.

If you don't want all those extra classes for expanded/collapsed/active trail, you can just remove them:

      {%
        set classes = [
          'item--' ~ item.title|clean_class,
        ]
      %}