2

I've this breadcrumb I've created, where I would like to show it as

Home > Main menu > Sub menu

Where sub menu is connected to a node. So when a user click on node, it must show the breadcrumb of the above format.

I've done this, but it is only giving

Home > Sub menu

Menu is missing.

function basis_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    $variables['breadcrumb'][] = array(
      'text' => $node->getTitle(),
      'url' => $node->URL()
    );

  }
}

2 Answers 2

3

Menu Breadcrumb might be what you're looking for.

1

If the url reflects the correct path, you can add this to your .theme file.

function hook_preprocess_breadcrumb(&$variables) {
  $variables['breadcrumb'] = array();
  $variables['node'] = \Drupal::routeMatch()->getParameter('node');

  /** @var \Drupal\Core\Link $link */
  foreach ($variables['links'] as $key => $link) {
    $variables['breadcrumb'][$key] = array('text' => $link->gettext(), 'url' => $link->getUrl()->toString());
  }

  // As of Drupal 8.1.3, core caches breadcrumb parent. This breaks what I'm trying to do. Good-bye to this caching rule.
  $variables['#cache']['contexts'][] = 'url';
}

EDIT

If the url is missing the 'Main menu' part, you can manually set the breadcrumb for any specific content type. Again in the theme file.

function hook_preprocess_breadcrumb(&$variables) {
  $variables['breadcrumb'] = array();
  $variables['node'] = \Drupal::routeMatch()->getParameter('node');
  $variables['type'] = \Drupal::routeMatch()->getParameter('node')->getType();

  switch($variables['type']) {

    case 'YOUR-CONTENT-TYPE':
      $variables['breadcrumb'] = array(
        array(
          'text' => 'Home',
          'url' => '/'
        ),
        array(
          'text' => 'Main menu',
          'url' => 'Main menu url'
        ),
        array(
            'text' => $variables['node']->getTitle(),
            'url' => $variables['node']->URL()
          ),
        );
      break;

    default:
      /** @var \Drupal\Core\Link $link */
      foreach ($variables['links'] as $key => $link) {
        $variables['breadcrumb'][$key] = array('text' => $link->gettext(), 'url' => $link->getUrl()->toString());
      }
      break;
  }

  // As of Drupal 8.1.3, core caches breadcrumb parent. This breaks what I'm trying to do. Good-bye to this caching rule.
  $variables['#cache']['contexts'][] = 'url';
}

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.