0

Is it possible to add a unique id or class to each li element in a menu, perhaps using a preprocess function? I want to be able to target each menu item individually with CSS.

I could probably use css rules like li:nth-child(1) etc, but I would rather add a unique ID or class to the element.

2 Answers 2

2

I use this module https://www.drupal.org/project/link_attributes

It allows you to add classes/ids to menu items by editing them through Drupal's core menu admin screens

0

You can use menus_attribute to add MANUALLY unique ids to each menu. I understand this is not practical if you have a big menu but sometimes just setting 1 or 2 unique ids is enough for CSS design purposes.

The alternative would be to use a THEMENAME_preprocess_menu in your THEMENAME.theme file. Drupal 8 is not easy to get mlid which is unique and don't change with reordering of menu items but I don't know an easy way to do it. So presenting a few options inside comments in the function itself.

function THEMENAME_preprocess_menu(array &$variables) {
  $id = 0;
  foreach ($variables['items'] as $key => $item) {
    $attribute = &$variables['items'][$key]['attributes'];

    //$key might change if the link is pointing to another place
    //but is also a very ugly id and some times very big
    //$attribute->setAttribute('id', $key);

    //so to get a smaller id from previous key 
    //use http://php.net/manual/en/function.hash.php
    $key_hash = hash('crc32b', $key);
    $attribute->setAttribute('id', $key_hash);

    //id will change once the order of menu items changes
    //or when items are added or deleted
    //$attribute->setAttribute('id', "id-" . ++$id);    

    //how does one get them mlid from the database which would stay the same no matter what
    //probably using a function call that uses 
    //https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x

    // can this be used ? 
    //http://www.drupalcontrib.org/api/drupal/drupal%21core%21includes%21menu.inc/function/menu_tree_all_data/8 
  }
}
1
  • Thank you for your answer, it seems like Drupal 8 is more difficult than Drupal 7 for doing this. I think I will just go with using the menu attributes module.
    – Ben
    Commented Jan 23, 2018 at 17:34

Your Answer

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

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