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 />

There are three ways variables can be passed through <strong>Drupal</strong>.t() depending on the<br />

first character of the variable:<br />

• Variables beginning with a ! are inserted as is, with no modification.<br />

• When a variable begins with an @ symbol the value is passed through<br />

<strong>Drupal</strong>.checkPlain(), a function that converts the string to plain text.<br />

HTML markup is converted to text that can be displayed.<br />

• % at the beginning of a variable will cause the variable to be passed through<br />

<strong>Drupal</strong>.checkPlain() and <strong>Drupal</strong>.theme('placeholder').<br />

Behaviors<br />

If you're familiar with writing jQuery, you know that the code you want to execute<br />

as early as possible in a page load is wrapped in something like the following:<br />

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

...<br />

});<br />

When the document is ready the code wrapped inside this function will be executed.<br />

This is a common pattern for jQuery-based JavaScript. <strong>Drupal</strong> provides a system<br />

that wraps and extends this concept called behaviors. Behaviors are attached and<br />

detached from a section of content. The most common usage is to attach a behavior<br />

to an entire page.<br />

Rewriting our Hello World example seen previously to use behaviors would look<br />

as follows:<br />

(function($) {<br />

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

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

'';<br />

}<br />

<strong>Drupal</strong>.behaviors.helloWorld = {<br />

attach: function(context, settings) {<br />

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

'Chicago'));<br />

}<br />

}<br />

})(jQuery);<br />

[ 303 ]

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

Saved successfully!

Ooh no, something went wrong!