How can I add an additional attribute to menu item I am using mega menu?

On element inspect my current menu url is displaying as :

<a class="we-mega-menu-li activeNav" title=""href="/clients/drupal/abc/fr/home#xyz" target="">

I need to create it as :

<a class="we-mega-menu-li activeNav" title=""  data-target="xyz" href="/clients/drupal/abc/fr/home#xyz" target="">

I have used menu links attribute module but its not working with mega menu any other suggestions by doing some custom code?

  • Is it dynamically generating menu or static menu?
    – Ajay Reddy
    Commented Aug 17, 2018 at 8:00
  • its is static menu only
    – user52318
    Commented Aug 17, 2018 at 8:15

2 Answers 2


You can use below code to set attributes. This will add an attribute to all links in the page. But make sure to add the condition check for your URL.

 * Implements template_preprocess_menu().
function THEME_preprocess_menu(&$variables) {
  foreach ($variables['items'] as $item) {
    $item['attributes']->setAttribute('data-target', 'YOUR TARGET NAME');
  • Sorry its not working for my case
    – user52318
    Commented Aug 17, 2018 at 11:53

Finally i found the solution by myself:

I have copied the twig file from mega menu module to our theme's directory we-megamenu-li.html.twig and make the following changes into it, now data- target values are dynamic .

<a class="we-mega-menu-li"   data-target="{{ href | split('#')[1] }}"   title="{{ attribute(attributes, 'description') }}" href="{{ href }}" target="{{ attribute(attributes, 'data-target') }}">something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.