“Learn how to create a Drupal 9 custom module to inject CSS into the header using a block, with example code and step-by-step instructions.”
Discover the power of Drupal 9 customization by adding custom CSS to the header using a block module. This blog post provides a comprehensive guide, complete with example code and detailed steps, empowering Drupal developers to enhance site styling efficiently.
In this tutorial, we'll cover the entire process of creating a custom module, defining a block, and injecting CSS styles directly into the header. The step-by-step instructions will include creating the module file, defining the block class, and implementing the necessary hooks to seamlessly integrate your custom styles.
Example Code:
Create the Custom Module:
// my_custom_module.info.yml name: 'My Custom Module' type: module core_version_requirement: ^8 || ^9 package: CustomDefine the Block Class:
// src/Plugin/Block/MyCustomBlock.php namespace Drupal\my_custom_module\Plugin\Block; use Drupal\Core\Block\BlockBase; /** * Provides a custom block with added CSS to the header. * * @Block( * id = "my_custom_block", * admin_label = @Translation("My Custom Block"), * category = @Translation("Custom") * ) */ class MyCustomBlock extends BlockBase { // Implement block build and other necessary methods. }Inject CSS into Header:
// my_custom_module.module function my_custom_module_preprocess_page(&$variables) { if ($block = \Drupal::service('plugin.manager.block')->createInstance('my_custom_module', [])) { $css = '.my-custom-styles { color: #3498db; }'; $variables['#attached']['html_head'][] = [ [ '#tag' => 'style', '#value' => $css, ], 'my_custom_module_css', ]; } }
This tutorial is perfect for Drupal developers looking to enhance their customization skills. By the end, you'll have a fully functional custom module injecting CSS into the header via a block, allowing for seamless styling modifications in Drupal 9.
