0

I am hoping there is a way to alter a menu link independent of menu.html.twig

Motivation is this example from Bootstrap theme menu.html.twig:

{% set link_title = item.title %}
{% set link_title %}{{ link_title }} <span class="caret"></span>{% endset %}

The Twig template is adding markup to the link $variables['text'] of hook_link_alter().

I'm altering the text of a menu link item but retaining any HTML it might have. I have the below which works:

function hook_link_alter(&$variables) {

  $linkText = $variables['text'];
  $cleanLinkText = rtrim(strip_tags($linkText));

  if ($cleanLinkText == 'string') {

    $linkMarkup = str_replace($cleanLinkText, '', $linkText);

    // c_Markup() returns a new TranslatableMarkup().
    // We have to pass back in the HTML.
    $markup = c_Markup($linkMarkup);

    $variables['text'] = $markup;

  }

}

Things like str_replace and trim are very powerful, but I would prefer I use the appropriate hook for the need.

Have worked with hook_preprocess_menu(&$variables, $hook) without better success.


Update: This also works and I am able to get the text without the markup. Yet it seems like a lot more work to cycle through all the entire menu tree.

function hook_preprocess_menu(&$variables, $hook) {

  foreach ($variables['items'] as &$key) {

    $title = rtrim(strip_tags($key['title']));

    if ($title == 'string') {

      $key['title'] = $markup;

    }

    foreach ($key['below'] as &$beKey) {

      if ($beTitle == 'string') {

        $beKey['title'] = $markup;

      }

    }

  }

}

I guess this answers my question but is there a more direct hook/method to use? Under $key['original_link'] I can see the protected Translatable Markup for the link title.

Your Answer

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

Browse other questions tagged or ask your own question.