6

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

1

3 Answers 3

7

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',
    ),
  ),
];
4

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') }}

1

You need to include the js file first in moduleName.libraries.yml. Then you can run, the alert function will work.

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.