3

How can I add HTML tags into menu title?

I'm also tryed the following code.

function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    $vars['items']['standard.front_page']['title']='<i class="icon-home"></i>';
  }
}

It also converts tags into HTML entities.

  • Have you tried overriding the template files? – Eyal Sep 24 '16 at 21:59
5

You need to tell drupal that the string is safe. When you use t() this is done automatically. But this would make no sense here, because there is nothing to translate.

In this case you can use an untranslatable markup:

use Drupal\Core\Render\Markup;

function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    if (isset($vars['items']['standard.front_page'])) {
      $vars['items']['standard.front_page']['title'] = Markup::create('<i class="icon-home"></i>');
    }
  }
}
  • I try to write this: foreach ($vars['items'] as $menu) {$menu['title'] = Markup::create($menu['title']);} but there is no result – Crantisz Sep 25 '16 at 10:17
  • But your code works – Crantisz Sep 25 '16 at 10:25
  • 1
    That the loop doesn't work, is not a drupal problem, this is php specific: You need a & before the loop variable, if you want to modify it: foreach ($vars['items'] as &$menu) – 4k4 Sep 25 '16 at 12:00
0

You can use supporting modules for this task. please check the following:

https://www.drupal.org/project/menuimage

https://www.drupal.org/project/menu_icons

Hope it will be helpful for you.

  • 1
    I know about these modules, but I need a solution for Drupal 8 (they for Drupal 7) – Crantisz Sep 24 '16 at 18:13
  • Already replied by @4k4, That's the perfect answer. – Suraj k Sep 25 '16 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.