Drupal 9: How to create a custom block

By Fernando Katsukawa, 14 January, 2023

This should also work for Drupal 8 and Drupal 10 versions.

Custom blocks are piece of contents, code or logic that you can put inside pages in Drupal.

To create custom blocks, you will need to have a custom module.

Inside the custom module, you will need to create/use the following directory structure:


Inside this directory structure, create a class, which you can name as MyCustomBlock.php


namespace Drupal\your_custom_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

 * Provides a custom block.
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My custom block")
 * )
class MyCustomBlock extends BlockBase {

   * {@inheritDoc}
  public function build() {
    return [
      '#type' => 'markup',
      '#markup' => 'This is your custom block content.'


This example MyCustomBlock class extends BlockBase, which will provide you some basic configuration and settings form.

Now you can enable your custom block using your website structure block admin page, like the others blocks provided by the Drupal core.

About the Author

Profile picture for user fkatsukawa

Fernando Katsukawa is a certified senior backend developer, who have been worked with Drupal in the last 12 years and counting...

Saved your precious time? Use the cup below to buy me a coffee!
buy me a coffee - cup