1

I need to implement a custom block using JavaScript. These are the steps I took.

  1. I created a custom module

  2. I created a custom block by creating a class which extends blockbase

  3. I created a JavaScript file

  4. I defined a library in libraries.yml file and included the JavaScript file

  5. I attached the library to the block using #attached

So far so good. In the JavaScript file, I am trying to use the open source Datatables library, but I am unable to add it.

This is the code that implements the block.

/**
 * @file
 * Contains \Drupal\custom_cms_blocks\Plugin\Block\TopNewsBlock.
 */

namespace Drupal\custom_cms_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an 'Active forum topics' block.
 *
 * @Block(
 *   id = "top_news_min_block",
 *   admin_label = @Translation("Top News Min Block"),
 *   category = @Translation("Custom CMS blocks"),
 * )
 */
class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '<table id="example_table"><thead><tr><th>Artist / Band</th><th>Album</th><th>Song</th></tr></thead><tbody><tr><td>Muse</td><td>Absolution</td><td>Sing for Absolution</td></tr></table>',
      '#attached' => array(
        'library' =>  array(      
          'https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     ); 
  } 

}

Can you explain me how I can include an external JavaScript file in a block?

3

Libraries don't work like that. You need a yourmodule.libraries.yml and define it there.

There's detailed documentation on https://www.drupal.org/developing/api/8/assets#external. The following is an example of how a library is defined.

angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }

Then, the library that you specify is yourmodule/nameofthelibrary, see https://www.drupal.org/developing/api/8/assets#render-array or any of the other examples on that page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.