I have a view which displays the title and teaser of each node. I also need each node's breadcrumb to display in the view results. I have created a hook_preprocess_node function in my theme with the intent of using the nodes' urls to get the breadcrumb. I have tried to get the $route_match to pass to the builder, but have not been successful. Is this the right approach? If so, how do I get the correct $route_match Interface to pass? The following generates an array but not the Interface that is required.

$path = $variables['url'];
$router = \Drupal::service('router.no_access_checks');
$routerMatch = $router->match($path);
$breadcrumbBuilder = \Drupal::service('easy_breadcrumb.breadcrumb');
$breadcrumb = $breadcrumbBuilder->build($routerMatch);
$variables['breadcrumb'] = $breadcrumb;

Comments

sassafrass created an issue. See original summary.

greg boggs’s picture

I hacked this together from Stack Exchange. I'm sure there's a much cleaner way to code that :)

https://drupal.stackexchange.com/questions/191548/how-do-i-build-breadcr...

/**
 * Override or insert variables into the node template.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function multcolibtheme_preprocess_node(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.library_locations.page_1') {
    
    // Initialize an array to store breadcrumbs for nodes in the view.
    $breadcrumbs = [];

    $node = \Drupal\node\Entity\Node::load($variables['node']->id());
    $routeName = $node->toUrl()->getRouteName();
    $routeParameters = $node->toUrl()->getRouteParameters();
    $route = Drupal::service('router.route_provider')->getRouteByName($routeName);
    $routeMatch = new Drupal\Core\Routing\RouteMatch($routeName, $route, $routeParameters, $routeParameters);
    $variables[easy_breadcrumb'] = Drupal::service('easy_breadcrumb.breadcrumb')->build($routeMatch)->toRenderable();
  }
}
greg boggs’s picture

I didn't add a template, and I'm not sure about the toRenderable() bit on the end there. But, that code should be close.

sassafrass’s picture

Awesome! That worked! Thank-you so much!

greg boggs’s picture

Status: Active » Fixed

Woot!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.