Sorry, you need to enable JavaScript to visit this website.
Skip to main content
Welcome to our website! Explore our services and portfolio.

Creating a Custom (Programmatic) Block to Output HTML in Drupal

Submitted by admin on
In Drupal 10 and 11,

you create a custom block by building a Plugin. Modern versions of Drupal (starting from 10.2) prefer PHP Attributes over the older "Annotation" style for defining plugins. 

 
 
Step 1: Create a Custom Module 
 
First, you need a module to house your block. Create a folder in your Drupal installation at /modules/custom/my_custom_block. 
 
Inside that folder, create a file named my_custom_block.info.yml: 
 
 
yaml
name: 'My Custom Block'
type: module
description: 'A module to create a block programmatically.'
core_version_requirement: ^10 || ^11
package: Custom
Use code with caution.
 
 
Step 2: Define the Block Plugin Class 
 
Create the directory structure src/Plugin/Block within your module folder. Inside that, create a file named MyHtmlBlock.php. 
 
 
php
<?php

namespace Drupal\my_custom_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Provides a 'My HTML Block' block.
 */
#[Block(
  id: "my_html_block",
  admin_label: new TranslatableMarkup("My Custom HTML Block"),
  category: new TranslatableMarkup("Custom")
)]
class MyHtmlBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Return a render array with the HTML content.
    return [
      '#markup' => '<div class="custom-block">
                      <h2>Hello World</h2>
                      <p>This block was created programmatically in 2026.</p>
                    </div>',
    ];
  }

}
Use code with caution.
 
Note: If you are on a version older than Drupal 10.2, you would use @Block annotations in a comment block instead of the #[Block] attribute. 
 
 
Step 3: Enable and Place the Block 
 
  1. Enable the module: Go to Extend in your admin menu or use Drush: drush en my_custom_block.
  2. Clear Caches: This is necessary for Drupal to discover the new plugin.
  3. Place the Block: Navigate to Structure > Block layout (/admin/structure/block).
  4. Find a region (e.g., Sidebar), click Place block, search for "My Custom HTML Block", and save it. 
  5.  
 
Customizing the HTML Output
 
Instead of raw #markup, it is best practice for complex HTML to use a Twig template. To do this, you would define hook_theme() in a .module file and return a theme name (e.g., '#theme' => 'my_custom_block_template') in your build() method. 
 
The following tutorial demonstrates the full process of creating a custom block plugin in modern Drupal versions:

Related video thumbnail

59s