Skip to main content

Drupal 8: How to add html tags (span,div,strong etc) in your Menu Item Title

Recently i had to add a custom svg icon per menu item. These icons were not in fontawesome or some other icon library. I had to add a span before the title so i could show them per menu item. This is how i did it.

use Drupal\Component\Render\FormattableMarkup;
 * Implements hook_preprocess_hook().
 * @inheritdoc
function customTheme_preprocess_menu(&$variables) {

  if (isset($variables['menu_name']) && $variables['menu_name'] === 'main') {

    foreach($variables['items'] as $key => $item) {

      $variables['items'][$key]['title'] = new FormattableMarkup('<span class="icon-block">&nbsp;</span><span>@title</span>', [
      '@title' => $variables['items'][$key]['title'],


Do not forget to add the namespace
use Drupal\Component\Render\FormattableMarkup;