Exporting a variable from PHP to JavaScript
Once we get beyond the rudimentary, we will frequently be faced with scenarios where the JavaScript will need to adapt based on the settings and user data which are stored in the database or provided by Drupal modules. In this recipe, we will look at how the Drupal API allows themers to seamlessly export variables from a module and make them available to JavaScript.
Getting ready
We will be using the mysite module created earlier in this book to hold our odds and ends. It is assumed that this module has been created and is enabled.
How to do it...
The following steps are to be performed inside the mysite module folder at sites/all/modules/mysite
.
Open the file
mysite.module
in an editor.Look for an implementation of
hook_init()
or, if unavailable, create one.Add the code to include our JavaScript file so that the
mysite_init()
function resembles something like the following:/** * Implementation of hook_init(). */ function mysite_init() { // Export a...