18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

<strong>Drupal</strong>.theme() will call the <strong>Drupal</strong>.theme.prototype.hello() function and pass<br />

in all the arguments, but the first one. This is useful because the theme can provide<br />

an override function. If a module provides a hello_world.js file as the one above,<br />

and a theme provides a JavaScript file with the following function, the output will<br />

be changed.<br />

(function($) {<br />

<strong>Drupal</strong>.theme.hello = function(text) {<br />

return '' + text + '';<br />

}<br />

})(jQuery);<br />

<strong>Drupal</strong>.theme() will call <strong>Drupal</strong>.theme.hello() instead of <strong>Drupal</strong>.theme.<br />

prototype.hello(). The theme can override the presentation in JavaScript this way.<br />

Translatable strings<br />

All the text inside the <strong>Drupal</strong> interface is translatable. The text within JavaScript<br />

can be translated as well. Inside the PHP code for <strong>Drupal</strong> the t() function is used<br />

for translations. Inside JavaScript the <strong>Drupal</strong>.t() function is used to handle<br />

translations.<br />

Continuing the Hello World module we can extend it to handle, say "hello" to<br />

different cities, where the "hello" part is translatable.<br />

(function($) {<br />

<strong>Drupal</strong>.theme.prototype.hello = function(text) {<br />

return '' + <strong>Drupal</strong>.t('Hello @city', {'@city': text}) + '';<br />

}<br />

$().ready(function() {<br />

$('#hello-world').html(<strong>Drupal</strong>.theme('hello', 'Chicago'));<br />

});<br />

})(jQuery);<br />

The part we are interested in is where it says:<br />

<strong>Drupal</strong>.t('Hello @city', {'@city': text})<br />

Here the string 'Hello @city' is a translatable string. The @city part is dynamic<br />

and will be filled in by the value of text. This setup enables translations<br />

to modify the string and still pass the dynamic portions through.<br />

[ 302 ]

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

Saved successfully!

Ooh no, something went wrong!