Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codezixo
Forked from jonpugh/Breadcrumbs.php
Created November 8, 2017 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codezixo/dcabd829c0129a3ab0a0e3f5c7f60e21 to your computer and use it in GitHub Desktop.
Save codezixo/dcabd829c0129a3ab0a0e3f5c7f60e21 to your computer and use it in GitHub Desktop.
Add Taxonomy Term to a Node's Breadcrumb in Drupal 8
<?php
// src/Breadcrumbs.php
namespace Drupal\modulename;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;
/**
* Class Breadcrumbs.
*
* @package Drupal\modulename
*/
class Breadcrumbs implements BreadcrumbBuilderInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
return $route_match->getRouteName() == 'entity.node.canonical'
&& $route_match->getParameter('node') instanceof NodeInterface;;
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$node = $route_match->getParameter('node');
$breadcrumb = new Breadcrumb();
// By setting a "cache context" to the "url", each requested URL gets it's own cache.
// This way a single breadcrumb isn't cached for all pages on the site.
$breadcrumb->addCacheContexts(["url"]);
// By adding "cache tags" for this specific node, the cache is invalidated when the node is edited.
$breadcrumb->addCacheTags(["node:{$node->nid->value}"]);
// Add "Home" breadcrumb link.
$breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
// Given we have a taxonomy term reference field named "field_section", and that field has data,
// Add that term as a breadcrumb link.
if (!empty($node->field_section->entity)) {
$breadcrumb->addLink($node->field_section->entity->toLink());
}
return $breadcrumb;
}
}
# modulename.services.yml
services:
modulename.breadcrumbs:
class: Drupal\modulename\Breadcrumbs
tags:
- { name: breadcrumb_builder, priority: 100 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment