вторник, 14 октября 2008 г.

JavaScript & jQuery Drupal theming


Query basics

Drupal 6.0 to 6.2 include jQuery 1.2.3. In Drupal 6.3 this was upgraded to jQuery 1.2.6, which at the time of writing is the latest version. If your site needs a later version of jQuery then check out the jQuery update module.

Default JavaScript file

Similarly to style.css, there is a new automatically included file named script.js for adding JavaScript code to a theme. The file should be placed in the theme’s home directory.

JavaScript theming

There is now a theming mechanism for JavaScript code. Together with the automatically included script.js, this allows theme developers more freedom in the domain of scripted events on Drupal sites. Often, people's JavaScript code produces markup that is inserted into the page. However, this may contain HTML that has been hard-coded into the script, which did not allow alteration of the inserted code.

Modules provide default theme functions in the Drupal.theme.prototype namespace. For example, if I wanted to make my theme function powered(to display a "powered by Drupal" icon), it would look like this

Drupal.theme.prototype.powered = function(color, height, width) {
return '";
}

The way I would call this is
$('.footer').append(Drupal.theme('powered', 'black', 135, 42));

That puts a button like

in the footer.

If I wanted to override this in my theme, maybe to include files in my theme directory instead of /misc, I would do so like this:

Drupal.theme.prototype.powered = function(color, height, width) {
return '";
}

This takes advantage of plain JavaScript. The above function would go in a theme's JavaScript file, avoiding the need for altering the related module's JavaScript files.

JavaScript theme functions are entirely free in their return value. They can vary from simple strings to complex data types like objects, arrays, and jQuery elements. Refer to the original (default) theme function to see what your custom theme function should return.

Still needed: jQuery intro, how to add aggregation (patch at http://drupal.org/node/119441) etc...