Translating strings in JavaScript

Last modified: June 4, 2009 - 10:18

The JavaScript library shipped with Drupal 6 includes ports of the t() and format_plural() functions, for formatting and translating strings that occur in your module and theme JavaScript code. The Drupal.t() and Drupal.formatPlural() functions work just like their PHP equivalents. They are also similar to their PHP counterparts in that you should use them with literal strings for all string arguments, both so that Drupal can pick the strings up for translation, and the translation template extractor can offer them for translation in templates.

All three types of placeholders, with identical escaping and theming, are available in both functions, so security is also taken care of. Examples of use:

var comments = Drupal.t('Comments');
var commentsOnType = Drupal.t('Comments to @type posts', {'@type': typeName});
var commentCount = Drupal.formatPlural(count, '1 comment', '@count comments');
var commentCountOnType = Drupal.formatPlural(count, '1 comment on @type posts', '@count comments on @type posts', {'@type': typeName});

The signatures of the two functions are Drupal.t = function(str, args) and Drupal.formatPlural = function(count, singular, plural, args). As you can see, unlike their PHP counterparts, the JavaScript functions do not allow for alternate language specification, since only the required strings are generated into the output page for use. Look into the source of drupal.js for more information on these functions.

It is important to note that automatic extraction does not work for packed JS files. For this reason, module authors should only include unpacked versions of their JS files. Drupal's JS aggregator will create a packed version from these files anyway.

 
 

Drupal is a registered trademark of Dries Buytaert.