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.

JavaScript in <strong>Drupal</strong><br />

API Documentation for hook_library_alter() is available at<br />

http://api.drupal.org/api/function/hook_library_<br />

alter/7<br />

Using renderable arrays<br />

A <strong>Drupal</strong> Renderable Array is the way much of the output for a <strong>Drupal</strong> page is<br />

represented before it is rendered into HTML. Theme functions, discussed in Chapter 3,<br />

<strong>Drupal</strong>'s Theme Layer, can return either a <strong>Drupal</strong> Renderable Array or HTML to output.<br />

If a Renderable Array is returned it will be rendered into HTML by drupal_render().<br />

If you are familiar with the Form API from previous versions of <strong>Drupal</strong> you've seen<br />

the Renderable Arrays. They are the arrays from Form API extrapolated to other uses.<br />

The Renderable Array for a form element might look like this:<br />

$form['options'] = array(<br />

'#type' => 'textfield',<br />

'#title' => t('Author name'),<br />

'#maxlength' => 25,<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 />

The #attached property on a renderable or form array can be used to add<br />

JavaScript, CSS, and libraries. The keys are as follows:<br />

• js is for JavaScript<br />

• css is used for CSS<br />

• library is used to add libraries<br />

For each item in a sections array, like js, the key is the data and the options are the<br />

value. If the value is omitted, the default options are assumed.<br />

Using renderable arrays and attaching the JavaScript, CSS, and libraries is important<br />

in several places throughout <strong>Drupal</strong> where caching of individual elements happen.<br />

An example is with blocks which can be cached. A common use case is when<br />

JavaScript is added to a block. If the JavaScript is added within the content of the<br />

block using drupal_add_js() it will be added when the block is not cached.<br />

Cached blocks do not rebuild the content so drupal_add_js() will not be called.<br />

[ 298 ]

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

Saved successfully!

Ooh no, something went wrong!