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;

hook_preprocess_menu

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10