With over a decade of web development experience, I specialize in Drupal (7, 8, 9, 10), CodeIgniter, Laravel, and WordPress. I offer extensive expertise in both module and theme development, providing customized solutions for complex projects. Whether you need to enhance an existing platform, create new features, or seek expert guidance, I'm here to assist. My dedication to delivering high-quality, efficient, and scalable solutions is unmatched. Feel free to contact me to explore how I can contribute to your project's success. Let's turn your ideas into reality!

“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:

  1. Create the Custom Module:

    // my_custom_module.info.yml
    name: 'My Custom Module'
    type: module
    core_version_requirement: ^8 || ^9
    package: Custom
  2. Define 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.
    }
  3. 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.

Posted by Sujan Shrestha
Categorized:
PREVIOUS POST
banner