Add Theme Suggestion to Menus using Menu Block in Drupal

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Menu Block gives you additional functionality around managing the display of menus in block regions. Drupal core allows you to add any menu such as main navigation, footer, etc… into any region and you can control how many menu levels should be displayed. Menu Block gives you additional options such as setting a fixed parent item, changing the block title, and more.

But the one feature of Menu Block I want to show you in this tutorial is the ability to add a custom theme hook suggestion to menus.

Getting Started

Before we begin, go download the Menu Block module.

Run the following command using Composer:

$ composer require drupal/menu_block

Go to Extend and search for menu block and install the module.

Menu block module

What are Theme Hook Suggestions

A theme hook suggestion tells the theme which template should be used. For example, if you turn on Twig debug in your Drupal site and view page source, you’ll see the suggestions and which template is being used.

theme files

This template information is vitally important when you’re theming a website especially if you’re new to Drupal.

Menu Block allows you to add a custom theme hook suggestion to your menus. This is useful for when you want to use the menu in multiple regions and have it use the same Twig template file.

The hook theme suggestions can be changed using code, but Menu Block allows you to change it from the block configuration page.

Change Theme Hook Suggestion

Make sure you’ve downloaded and installed the Menu Block module.

1. Go to Block layout and click on “Place block” next to Sidebar.

Sidebar - place block

2. Search for the main navigation and click on “Place block”.

3. Click on “HTML and style options” and add the suggestion into “Theme hook suggestion”.

I added main__primary_sidebar

If you view the page source again, you should see menu--main--primary-sidebar.html.twig as an option under “FILE NAME SUGGESTIONS”.

Summary

If you want to customize the main navigation menu template and reuse it in different regions, then adding the theme hook suggestion via Menu Block is the way to go.

About The Author

Leave a Comment

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

Scroll to Top