Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 Custom Block how to attach JavaScript ?

Tags:

drupal-8

I have created a custom block successfully and just want to call java script alert function on the block. I have created a .js file .The issue is how to call the function declared in the javascript throgh array render in build function of the BLOCK PHP

like image 870
Ankur Garg Avatar asked Jan 02 '23 19:01

Ankur Garg


2 Answers

Please elaborate the question. As per my understanding try this one. Reference

Attaching js to a render array of a Block Plugin

To give another example of attaching a library to a render array, If you are building a block plugin in your module, you can attach the libraries to the render array in the build() function of your class extending the BlockBase class (as of Drupal 8 beta 6).

return [
  '#theme' => 'your_module_theme_id',
  '#someVariable' => $some_variable,
  '#attached' => array(
    'library' => array(
      'your_module/library_name',
    ),
  ),
];
like image 106
user3575353 Avatar answered Jan 10 '23 02:01

user3575353


You can attach a library to a Block in a twig file:
1) supposing the block name is: block--foobar.html.twig
2) and you created a library in THEME.libraries.yml file called: contact-js
3) => you can attach the library to the Block by calling this in block--foobar.html.twig :
{{ attach_library('THEME/contact-js') }}

like image 25
Nysso Avatar answered Jan 10 '23 02:01

Nysso