How to allow html tag in menu in Drupal 8. For example if use home @reg used in menu title it display the html tag.
2 Answers
Following solution works:
use Drupal\Core\Render\Markup; /** * Implements hook_preprocess_HOOK() */ function YOURTHEME_preprocess_menu(&$variables){ foreach($variables['items'] as &$link){ $link['title'] = Markup::create($link['title']); } } Source: Allow html into menu item names - Solution for Drupal 8
I recommend to use a plugin for this. Full tutorial here: Create a menu link with html markup in drupal 8
namespace Drupal\MYMODULE\Plugin\Menu; use Drupal\Core\Menu\MenuLinkDefault; /** * A menu link that displays number of points. */ class MyMessagesMenuLink extends MenuLinkDefault { /** * {@inheritdoc} */ public function getTitle() { $count = 0; if(\Drupal::currentUser()->isAuthenticated()) { // Load in your count here ... } return $this->t('My messages <span class="badge badge-dark">@count</span>', ['@count' => $count]); } /** * {@inheritdoc} */ public function getCacheMaxAge() { return 0; } } - blogs tend to go away, but stackexchange sticks around. Could you copy the best excerpts of the ideas of that blog here?greggles– greggles2020-01-06 17:54:21 +00:00Commented Jan 6, 2020 at 17:54
- 1Ok, pasted it in the original answer.Stef Van Looveren– Stef Van Looveren2020-01-07 07:58:05 +00:00Commented Jan 7, 2020 at 7:58