[custom block module]Correcting Heredoc Syntax and Attaching JS

To create a custom block module in Drupal that includes both HTML and JavaScript, you'll need to follow several steps. This guide assumes you're using Drupal 8 or Drupal 9, given their similarity in handling custom modules and blocks.

Step 1: Create the Module Folder and Files

  1. Module Folder: Navigate to /modules/custom in your Drupal installation (create the custom directory if it doesn't exist). Create a new folder named html_js_custom_block.

  2. .info.yml File: Inside html_js_custom_block, create a file named html_js_custom_block.info.yml. This file defines the basic metadata about your module. Populate it with the following content:

    yaml
    name: 'HTML and JS Custom Block'
    type: module
    description: 'A custom block that includes HTML and JavaScript.'
    package: Custom
    core_version_requirement: ^8 || ^9
    dependencies:
      - drupal:block
    
  3. .module File: This file isn't strictly necessary for this simple example, but it's standard to include it for more complex functionality in the future. Create html_js_custom_block.module without any content for now.

Step 2: Create the Block Plugin

  1. Block Plugin Directory: Inside the html_js_custom_block directory, create the following structure: /src/Plugin/Block.

  2. Block Plugin Class: Within the /Block directory, create a file named CustomHTMLJSBlock.php. Add the following PHP code:

    php
    <?php
    
    namespace Drupal\html_js_custom_block\Plugin\Block;
    
    use Drupal\Core\Block\BlockBase;
    use Drupal\Core\Block\BlockPluginInterface;
    
    /**
     * Provides a custom block with HTML and JavaScript.
     *
     * @Block(
     *   id = "custom_html_js_block",
     *   admin_label = @Translation("HTML and JS Custom Block"),
     *   category = @Translation("Custom")
     * )
     */
    class CustomHTMLJSBlock extends BlockBase implements BlockPluginInterface {
      
      /**
       * {@inheritdoc}
       */
      public function build() {
        $build['content'] = [
          '#markup' => '<div id="custom-content">This is custom HTML content.</div>',
          '#attached' => [
            'library' => [
              'html_js_custom_block/custom_js'
            ]
          ]
        ];
    
        return $build;
      }
    }
    

Step 3: Add JavaScript

  1. JavaScript File: Create a new directory js in your module directory (/modules/custom/html_js_custom_block). Inside, create a folder 'js' and inside create a file named custom.js with the following content:

    javascript
    document.addEventListener('DOMContentLoaded', function () {
      var element = document.getElementById('custom-content');
      if (element) {
        element.innerHTML += '<p>Added with JavaScript!</p>';
      }
    });
    
  2. Declare the Library: In the root of your module directory, create a file named html_js_custom_block.libraries.yml. Add the following content to define your JavaScript file as a library:

    yaml
    custom_js:
      version: 1.0
      js:
        js/custom.js: {}
      dependencies:
        - core/jquery
        - core/drupal
    

Step 4: Install and Enable the Module

  • Enable the Module: Go to the Extend page on your Drupal site (/admin/modules), find "HTML and JS Custom Block", and enable it. Alternatively, use Drush: drush en html_js_custom_block.

Step 5: Place the Block on Your Site

  • Place the Block: Navigate to the Block layout page (/admin/structure/block), find the region you want to place your custom block in, and click "Place block" for the "HTML and JS Custom Block". Configure any necessary settings and save.

Step 6: Verify Everything Works

Visit the pages where you placed the block to ensure that the HTML and JavaScript are rendering and functioning as expected.

This setup integrates HTML content directly within the block and uses an attached JavaScript library for functionality, allowing for a clean separation of concerns and leveraging Drupal's robust API for asset management.

留言

此網誌的熱門文章

Install Drupal 10 with composer in XAMPP htdocs OR PHP Command

fix drupal 11 install error