Contents
How to pass PHP variable to JavaScript in Drupal?
And in MODULENAME.js use the following one. In this way, you can pass your PHP variable to JavaScript, and use it. For Drupal 8, drupal_add_js () was removed (it was deprecated in Drupal 7 already) => see this for further information.
How to pass variable to drupal.mycustomblock.test?
Drupal modules should use behaviors. See the first and the last line of the code I copied here. Your JavaScript code should use the same lines, and access the settings with drupalSettings.mycustomblock.test. Thanks for contributing an answer to Drupal Answers!
Why does Drupal not render anything in PHP?
The code doesn’t work because the build () method doesn’t return anything, which for PHP is like returning NULL. (In other words, you are telling Drupal not to render anything.) If you fix that, then you would also have to attach the library to the same variable to which you attach the settings.
How to use Drupal add JS in JavaScript?
You should use drupal_add_js () in your module, there is no need to output the variable in your .tpl.php: And in your JavaScript, you can the access the value in Drupal.settings.YOURMODULE.testvar: Direct usage of global variables (as suggested in your code sample) is a discouraged practice in JavaScript as it clutter the global namespace.
How to add a file to a Drupal page?
The following actions can be performed using this function: Add a file (‘file’): Adds a reference to a JavaScript file to the page.
When to use inline JavaScript in Drupal 7?
Add inline JavaScript code (‘inline’): Executes a piece of JavaScript code on the current page by placing the code directly in the page (for example, to tell the user that a new message arrived, by opening a pop up, alert box, etc.). This should only be used for JavaScript that cannot be executed from a file.