Translatable Strings In Drupal JavaScript

Drupal is known for being highly translatable. The localization team has done a fantastic job building out tools to make Drupal translatable and it’s rare to find a module that doesn’t properly wrap its strings in the t() function or the lesser known format_plural() function. While the Drupal community is doing fairly well on the PHP side, many people don’t know there is a translation system for Drupal JavaScript as well through the use of the Drupal.t() and Drupal.formatPlural() functions.

Drupal.t()

`Drupal.t()` is a counterpart to the `t()` function in PHP. Unfortunately there is no great API documentation site for the JavaScript included in Drupal. Luckily, the usage is almost identical to what we see in PHP.

For example, to make a simple string translatable you could do something like:

var foo = Drupal.t('A translatable string.');

Passing replacements into Drupal.t() works just like the t() function. The replacement keys act based on the first character of the key.

  • Variables that start with ! will be passed in as is.
  • When a variable begins with @ it is passed through `Drupal.checkPlain()`, the JavaScript counterpart to `check_plain()`.
  • Variables that start with % will be escaped and passed trough the placeholder JavaScript theme function.

For example:

var args = {};
args['!url'] = 'http://example.com';
args['%name'] = 'John Doe';

var foo = Drupal.t('%name is the owner of !url', args);

Drupal.formatPlural()

Formatting plural strings is not something we often think about when it comes to translations. But, plural forms is part of translations and something we need to consider. The JavaScript counterpart to the PHP `format_plural()` function is `Drupal.formatPlural()`. The API for using the function is the same. For example:
var bar = Drupal.formatPlural(count, '@name has 1 site.', '@name has @count sites.', {'@name': personName});

Drupal has the tools to make our JavaScript translatable. Lets put them to good use. For more details see the Drupal Handbook on translations.