How to Create a Custom Block in Drupal 8

‘Blocks’ in Drupal are pieces of content that can be placed anywhere throughout the site. They are an integral part of Drupal and the way it displays information. While Drupal has a variety of useful blocks out of the box for most scenarios, there might be times when custom blocks are required. That is what I’ll be addressing in this post, by going through how to create a custom block in Drupal 8.

There are two ways in which you can create a custom block:

Through Drupal’s own GUI, or

Programmatically.

Via Drupal GUI

This method is pretty straightforward and easier than creating a block programmatically. However, it also is less flexible and customizable than programmatically creating a block.

Now, go back to custom block library and click the blue ‘Add custom block’ button, to add the block to your library.

The next step is to simply place the block into your desired region by navigating to admin -> structure -> block layout.

Programmatically Creating Block

This method requires a little more understanding of the way Drupal works, however, once you get the hang of it, it gets pretty easy.

Create a module

In Drupal 8, it is necessary to create an info.yml file that contains the metadata for every custom module, theme or plugin you create. Similarly, for our custom block, we will need to create an info.yml file in the ‘modules/custom’ directory. Note that if the custom folder isn’t already created, you will need to create it. For creating a custom block, we will need to make a custom module.

Now create an ‘info.yml’ file such as ‘custom_block_example.info.yml’. Inside this file enter following: