Creating a Custom (Programmatic) Block to Output HTML in Drupal
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
- Enable the module: Go to Extend in your admin menu or use Drush:
drush en my_custom_block. - Clear Caches: This is necessary for Drupal to discover the new plugin.
- Place the Block: Navigate to Structure > Block layout (
/admin/structure/block). - Find a region (e.g., Sidebar), click Place block, search for "My Custom HTML Block", and save it.
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:
59s
Tags
Recent content
-
1 hour 5 minutes ago
-
1 week ago
-
1 week 1 day ago
-
1 week 1 day ago
-
1 week 1 day ago
-
1 week 6 days ago
-
2 weeks ago
-
2 weeks 1 day ago
-
2 weeks 1 day ago
-
2 weeks 2 days ago