Adding Badges to Drupal Bootstrap Menu Items



I could give a long explanation about why you might want to do this or why you should or shouldn't do it a certain way, but you already know why you want to do it and this way works using Drupal conventions so let's skip all that and get down to business. The first thing you'll need is a way to get the content of your badge. In the example above I am retrieving the number 12, which happens to be the number of upcoming 'Coverage Calendar' events/appointments that the user has. Yours might be the number of messages in someone's inbox or their blood type (I won't ask... your business is your own).

The magic to make that number or string show up (dynamically) in the menu item is here:



Every Drupal theme_* looks for a preprocess version of itself. Okay that isn't exactly how it works, but it's the easiest explanation for now. The main bootstrap_menu_link function is in your theme folder, and only one iteration of that function can exist per theme. You should not put this function in any module. Instead you can implement theme_preprocess_menu_link in your module and in as many modules as need it. This hook has no concrete documentation on the Drupal API Reference, but it works the same way as the non-preprocess hook. You may find the reference here.

Badge-away!