-1

I want to add custom classes to the anchor tag in the main menu.

enter image description here

I implemented hook_preprocess_menu(), but it assigned the classes to the <ul> tag and I want to add the classes to the <a> tag.

The code I am using is the following one.

function menu_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    if (!isset($variables['attributes']['class'])) {
      $variables['attributes']['class'] = [];
    }
    $data = \Drupal::state()->get('my_data', 'bar');
    $variables['attributes']['class'][] = 'my-class';
  }
}
  • Welcome to Drupal Answers :) Unfortunately we don't know what you've tried yourself so far and where exactly you are stuck right now. Therefore we can't tell you what's maybe wrong with you current approach. Please update your question to share your current approach with us. Many thanks. – leymannx Oct 1 at 11:15
  • i think its clear. updated – afridi Oct 4 at 6:00
  • still not working . see code – afridi Oct 4 at 7:05
  • And the other answer from the linked question? In the template? The question actually got hold of $item first. – leymannx Oct 4 at 7:09
0

Try to store your class in a variable out attributes:

function menu_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['my_magic_class'] = 'my-class';
  }
}

Now you have to override menu.html.twig template into your theme template folder

...
<a class="menu-item {{ my_magic_class }}" OTHER_LINK_ATTRIBUTES>LINK_TEXT</a>
...

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.