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:

Result

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:

Step 3: Clear Cache and Test

You may have to clear the cache every time you make changes.

Tagged with: , ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *

*