I'm using the sitemap module and i need to get the menu link depth in my preprocess function (template_sitemap_menu_link). I'm trying to do that by accessing the MenuLinkContent object with

    $menu_link_obj = $variables['element']['#original_link'];

There is a getParent() method I can access to check if this is a level zero item, but no way to check for depth. I could always loop trough getParent() until I get NULL and count the number of iterations, but that seems like a bad practise to me. Is there an alternative?


Here is our approach:

$menu_link = $variables['element']['#original_link'];

$depth = 0;
$parent = $menu_link->getParent();
if ($parent) {
  while ($parent) {
    $parent_parts = explode(':', $parent);

    $parent_entity = \Drupal::service('entity.repository')->loadEntityByUuid($parent_parts[0], $parent_parts[1]);
    $parent = $parent_entity->get('parent')->get(0)->value;
    $depth ++;

Hope to help

  • 1
    Anyone coming across this, it will cause an error when trying to access the value for $parent_entity. Use $parent = $parent_entity->get('parent')->get(0) ? $parent_entity->get('parent')->get(0)->value : NULL; will solve this, that we check for the parent first.
    – supersize
    Nov 17 '20 at 21:22

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.