Skip to main content

Drupal 8: Adding classes to menus

Submitted by on Sun, 12/20/2015 - 16:10

If you ever need to add a specific class to a Drupal 8 menu, this is two ways to go about it.

Preprocess hooks

They still exists in Drupal 8, and very much in the theme layer. But not very well documented, and at the time of writing, i could find anything in the docs about this very hook.

The hook you need to implement is hook_preprocess_menu() and you need to do it in your MYTHEME.theme file. This is a more specific version of the general hook_preprocess, which is somewhat documented.

Anyways, this is how you would go about adding a class to the menu:

 * Implements hook_preprocess_menu().
function MYTHEME_preprocess_menu(&$variables) {
  // Probably you would only need to add it to a specific menu.
  if ($variables['menu_name'] === 'main') {
    $variables['attributes']['class'][] = 'my-class';

Override template

If you need to do more than adding one or two classes, you probably should override the template with your own version. The current Drupal 8.0.1 use the template found in /core/themes/stable/templates/navigation/menu.html.twig. So copy this file to your own template folder in your theme directive, and your good to go.

Making the template more specific

Now the template we just added to our own theme, would be used for all menus across the site. This is often not what you need. Luckily it's possible, and quite easy, to make the template specific to one menu. Enabled theme debugging, as describe in this article, about half way down, and inspect your menu to get the theme hook suggestion:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'menu__main' -->
   * menu--main.html.twig
   x menu.html.twig


Comment? Tweet me