I need to implement a custom block using JavaScript. These are the steps I took.
I created a custom module
I created a custom block by creating a class which extends blockbase
I created a JavaScript file
I defined a library in libraries.yml file and included the JavaScript file
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?