In a node preprocess hook I am getting breadcrumbs for the currently viewed node by doing the following:
$vars['breadcrumb'] = Drupal::service('breadcrumb')
->build(Drupal::routeMatch())->toRenderable();
This works fine as it uses Drupal::routeMatch()
to get the matched route for the current request.
But I also want to get the breadcrumb for each node in a listing of several nodes. In this case I cannot use Drupal::routeMatch()
since I want to get the breadcrumb for each node in the listing, not the current page. The problem is I cannot find a way of getting a RouteMatchInterface object (needed by the BreadcrumbBuilder) from a node object. I can get the url containing route information via $node->urlInfo()
but there seems to be no way of getting from there to a route match either.
How can this be done?
Edit:
I found a way to get the route match for a certain node. Not sure if it's the ideal way but it gets the job done:
$routeName = $node->urlInfo()->getRouteName();
$routeParameters = $node->urlInfo()->getRouteParameters();
$route = Drupal::service('router.route_provider')->getRouteByName($routeName);
$routeMatch = new RouteMatch($routeName, $route, $routeParameters);
However passing the $routeMatch
into PathBasedBredcrumbBuilder::create
does not generate bredcrumbs for that route!
On closer inspection it seems that the built-in PathBasedBreadCrumbBuilder
class completely ignores the passed in $routeMatch
parameter and instead builds the breadcrumbs using the path of the current page, fetched using the injected RequestContext object. I think I would need to swap out this service with my own implementation which uses the passed in parameters somehow. To be continued...