18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10<br />

If a renderable array is used instead with attached JavaScript, the renderable array<br />

is cached which contains the calls to the JavaScript. When the cached content is<br />

rendered and JavaScript, CSS, then the libraries included in the renderable array<br />

will be added to the page.<br />

An example that adds JavaScript and CSS to the output of a block would look like<br />

the following:<br />

$output['content'] = array(<br />

'#value' => 'The content of the block.',<br />

'#attached' => array(<br />

'css' => array(<br />

drupal_get_path('module', 'hello_world') . '/example.css',<br />

),<br />

'js' => array(<br />

"alert('Hello World!')" => array('type' => 'inline'),<br />

),<br />

),<br />

);<br />

Altering JavaScript<br />

JavaScript added to a page has a last chance to be altered before being rendered to<br />

the output page. Just before the JavaScript is rendered in HTML it is passed through<br />

hook_js_alter(). A module that implements hook_js_alter() has a last chance<br />

to act on or change the JavaScript.<br />

An example of this would be if a module wants to swap out the compressed version<br />

of jQuery with an uncompressed version. This would be helpful for debugging<br />

purposes. In the example, we will call the module jQuery Uncompressed. In the<br />

jquery_uncompressed.module file hook_js_alter() would look like the following:<br />

/**<br />

* Implements hook_js_alter().<br />

*/<br />

function jquery_uncompressed_js_alter(&$javascript) {<br />

$path = drupal_get_path('module', 'jquery_uncompressed')<br />

$javascript['misc/jquery.js']['data'] = $path . '/jquery.<br />

uncompressed.js';<br />

}<br />

The $javascript array passed in contains all the JavaScript to be added to the<br />

current page. This hook is called just before JavaScript is rendered to be added to the<br />

page. This is the last point to alter it.<br />

[ 299 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!