Skip to content

Instantly share code, notes, and snippets.

@welly
Created September 9, 2024 14:28
Show Gist options
  • Save welly/95d612ea091b3a6307ce2e0bcf5d8deb to your computer and use it in GitHub Desktop.
Save welly/95d612ea091b3a6307ce2e0bcf5d8deb to your computer and use it in GitHub Desktop.
services:
custom_breadcrumbs.breadcrumbs:
class: Drupal\custom_breadcrumbs\Breadcrumb\CustomBreadcrumbs
tags:
- { name: breadcrumb_builder, priority: 1015 }
<?php
namespace Drupal\custom_breadcrumbs\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Url;
class CustomBreadcrumbBuilder implements BreadcrumbBuilderInterface {
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
\Drupal::logger('custom_breadcrumbs')->debug(print_r($route_match->getRouteName(), TRUE));
return $route_match->getRouteName() === 'entity.node.canonical';
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$node = $route_match->getParameter('node');
$breadcrumb = new Breadcrumb();
$breadcrumb->addCacheContexts(["url"]);
$breadcrumb->addCacheTags(["node:{$node->nid->value}"]);
\Drupal::logger('custom_breadcrumbs')->debug(print_r($route_match->getRouteName(), TRUE));
$breadcrumb->addLink(Link::createFromRoute('Home Sweet Home', '<front>'));
$breadcrumb->addLink(Link::fromTextAndUrl($node->getTitle(), Url::fromRoute('entity.node.canonical', ['node' => $node->id()])));
return $breadcrumb;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment