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
-
3Welcome to Stack Overflow! Please edit your question to show the code you have so far. You should include at least an outline (but preferably a minimal reproducible example) of the code that you are having problems with, then we can try to help with the specific problem. You should also read How to Ask.– Toby SpeightFeb 14, 2018 at 12:04
3 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',
),
),
];
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') }}
You need to include the js file first in moduleName.libraries.yml
. Then you can run, the alert function will work.