old wagon with signs in it

Create a custom breadcrumb builder in Drupal 9

Tan Nguyen

|

In Drupal 9, you can create a custom breadcrumb builder by defining a custom module and implementing the necessary hooks and services. Breadcrumbs are used to navigate through the hierarchy of content on a Drupal site. Here's a step-by-step guide to creating a custom breadcrumb builder.

  1. Create a Custom Module: If you don't already have a custom module, create one. Follow these steps:

    a. Create a new folder for your module inside the modules/custom directory in your Drupal installation. Give it a suitable name, such as "custom_breadcrumb."

    b. Inside your module folder, create a custom_breadcrumb.info.yml file and a custom_breadcrumb.module file.

  2. Create a Breadcrumb Builder Service. 

Create custom_breadcrumb.services.yml​​​​​​

services:
  custom_breadcrumb.breadcrumb_builder:
    class: Drupal\custom_breadcrumb\CustomBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 1004 }

 

Create a class for your custom breadcrumb builder

// src/CustomBreadcrumbBuilder.php


namespace Drupal\custom_breadcrumb;




use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Symfony\Component\DependencyInjection\ContainerInterface;


class CustomBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  public function __construct() {
    // Constructor logic, if needed.
  }


  public function applies(array $attributes) {
    // Determine if this breadcrumb builder should be used.
    // You can check the current path or other conditions here.
  }


  public function build(array $attributes) {
    $breadcrumb = new Breadcrumb();
    
    // Build the breadcrumb, adding links as necessary.
    $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));
    $breadcrumb->addLink(Link::createFromRoute('Custom Page', '<current>'));

    return $breadcrumb;
  }
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word