Drupal 8 Make Breadcrums awesome

Take full control over drupal 8 breadcrums  a contrib module will never be exactly what you need so here is how:
if you cant do it in hook_system_breadcrumb_alter see my examples on there too (taggartj).

First in your module make a new service:

  my_module.breadcrumb:
      class: Drupal\my_module\CustomBreadCrumbBuilder
      arguments: ['@request_stack']
      tags:
        - { name: breadcrumb_builder, priority: 701 }

Then in your CustomBreadCrumbBuilder.php (my_module/src/CustomBreadCrumbBuilder.php) or what ever namespace you use.

<?php

namespace Drupal\my_module;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a breadcrumb node type X pages.
 */
class CustomBreadCrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var RequestStack
   */
  protected $requestStack;

  /**
   * {@inheritdoc}
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    if ($route_match->getRouteName() == 'entity.node.canonical') {
      $node = $this->requestStack->getCurrentRequest()->get('node');
      if ($node->getType() === 'content_type_x' || $node->getType() == 'content_type_y') {
        return TRUE;
      }
      $path = $this->requestStack->getCurrentRequest()->getPathInfo();
      if ($path == '/somepath' || $path == '/some-other-path') {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    if ($route_match->getRouteName() == 'entity.node.canonical') {
      $node = $this->requestStack->getCurrentRequest()->get('node');
      $type = $node->getType();
      $breadcrumb->addLink(Link::createFromRoute($this->t('beer'), '<nolink>'));
      if ($type === 'content_type_x') {
        $breadcrumb->addLink(Link::fromTextAndUrl(t('title it up '), Url::fromUri('internal:/some-other-path')));
      }
      if ($type == 'content_type_y') {
        $breadcrumb->addLink(Link::fromTextAndUrl(t('Some cool title'), Url::fromUri('internal:/some-path')));
      }
    }
    return $breadcrumb;
  }

}

 

Category: