3 namespace Drupal\taxonomy;
5 use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
6 use Drupal\Core\Breadcrumb\Breadcrumb;
7 use Drupal\Core\Entity\EntityManagerInterface;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\Core\StringTranslation\StringTranslationTrait;
13 * Provides a custom taxonomy breadcrumb builder that uses the term hierarchy.
15 class TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {
16 use StringTranslationTrait;
21 * @var \Drupal\Core\Entity\EntityManagerInterface
23 protected $entityManager;
26 * The taxonomy storage.
28 * @var \Drupal\Taxonomy\TermStorageInterface
30 protected $termStorage;
33 * Constructs the TermBreadcrumbBuilder.
35 * @param \Drupal\Core\Entity\EntityManagerInterface $entityManager
38 public function __construct(EntityManagerInterface $entityManager) {
39 $this->entityManager = $entityManager;
40 $this->termStorage = $entityManager->getStorage('taxonomy_term');
46 public function applies(RouteMatchInterface $route_match) {
47 return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
48 && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
54 public function build(RouteMatchInterface $route_match) {
55 $breadcrumb = new Breadcrumb();
56 $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
57 $term = $route_match->getParameter('taxonomy_term');
58 // Breadcrumb needs to have terms cacheable metadata as a cacheable
59 // dependency even though it is not shown in the breadcrumb because e.g. its
60 // parent might have changed.
61 $breadcrumb->addCacheableDependency($term);
62 // @todo This overrides any other possible breadcrumb and is a pure
63 // hard-coded presumption. Make this behavior configurable per
64 // vocabulary or term.
65 $parents = $this->termStorage->loadAllParents($term->id());
66 // Remove current term being accessed.
67 array_shift($parents);
68 foreach (array_reverse($parents) as $term) {
69 $term = $this->entityManager->getTranslationFromContext($term);
70 $breadcrumb->addCacheableDependency($term);
71 $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
74 // This breadcrumb builder is based on a route parameter, and hence it
75 // depends on the 'route' cache context.
76 $breadcrumb->addCacheContexts(['route']);