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.
Notes:
- For performance reasons, Drupal caches the js files it has parsed. So, when you add or change strings in a js file, you have to clear the cache to have Drupal pick up the new strings and make them available for translation.
- 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.
Good information about translate strings in java script.
ReplyDeleteDrupal Development Services