Adding Level Number Class to Menu Items in Drupal 8
This is a quick post showing how to add level classes to menu items in Drupal 8.
Here’s the result, showing the additional menu--level-N and menu-item--level-N classes:
Step 1: Create a New Twig template File
Determine which Twig template you need to override. I recommend reading the official docs on this. In my case, for a menu called infofor, I copied docroot/core/themes/classy/templates/navigation/menu.html.twig to docroot/themes/custom/mytheme/templates/navigation/menu--infofor.html.twig .
Step 2: Update the Twig Code
The best way to see the changes is to see a diff. Notice how few changes it takes to achieve the desired result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
{# /** * @file * Theme override to display a menu. * * Available variables: * - menu_name: The machine name of the menu. * - items: A nested list of menu items. Each menu item contains: * - attributes: HTML attributes for the menu item. * - below: The menu item child items. * - title: The menu link title. * - url: The menu link url, instance of \Drupal\Core\Url * - localized_options: Menu link localized options. * - is_expanded: TRUE if the link has visible children within the current * menu tree. * - is_collapsed: TRUE if the link has children within the current menu tree * that are not currently visible. * - in_active_trail: TRUE if the link is in the active trail. */ #} {% import _self as menus %} {# We call a macro which calls itself to render the full tree. @see http://twig.sensiolabs.org/doc/tags/macro.html #} {{ menus.menu_links(items, attributes, 0) }} {% macro menu_links(items, attributes, menu_level) %} {% import _self as menus %} {% if items %} {% if menu_level == 0 %} <ul{{ attributes.addClass('menu') }}> {% else %} - <ul class="menu"> + <ul class="menu menu--level-{{ menu_level + 1}}"> {% endif %} {% for item in items %} {% set classes = [ 'menu-item', item.is_expanded ? 'menu-item--expanded', item.is_collapsed ? 'menu-item--collapsed', item.in_active_trail ? 'menu-item--active-trail', + 'menu-item--level-' ~ (menu_level + 1) ] %} <li{{ item.attributes.addClass(classes) }}> {{ link(item.title, item.url) }} {% if item.below %} {{ menus.menu_links(item.below, attributes, menu_level + 1) }} {% endif %} </li> {% endfor %} </ul> {% endif %} {% endmacro %} |
Step 3: Clear Cache and Test
You may have to clear the cache every time you make changes.