Converting menu items to font-awesome icons in Drupal 8 menu

Converting menu items to font-awesome icons in Drupal 8 menu

Transforming Drupal 8 menus in the social media icons list.
Vladimir Roudakov

Social media icons are common replacement for standard menu items.

Most of the social media icons are available as free version of Font Awesome library and corresponding Drupal module. You would need to install both.

Drupal 8 menu items do display title text by default.

In order to convert text like fab fa-gitlab into we need to do the following modifications:

  • use theme preprocess function e.g. mytheme_preprocess_menu__footer
  • detect if menu title starts with fas fa- or fab fa-
  • replace text with <i> tag e.g. <i class="fab fa-gitlab"></i>

The example below shows preprocess function for footer menu

<?php /** * @file * My theme file. */ use Drupal\Core\Render\Markup; /** * Implements template_preprocess_menu__footer(). */ function mytheme_preprocess_menu__footer(&$variables) { // Convert menu to HTML if contains `fas fa-` or `fab fa-`. foreach ($variables['items'] as $menu_id => $menu) { $title = $variables['items'][$menu_id]['title']; if ( (strpos($title, 'fas fa-') === 0) || (strpos($title, 'fab fa-') === 0) ) { $variables['items'][$menu_id]['title'] = Markup::create('<i class="' . $title . '"></i>'); } } }