blog-banner

Translatable Strings in Drupal JavaScript

  • FORMAT_PLURAL()
  • Javascript
  • T()
  • Translation

Drupal t 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 contrib 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 Drupal.t() functions and Drupal.formatPlural() functions.

Drupal.t() function

Drupal.t() function is the counterpart to the t() function in PHP. Generally, it is known to all Drupal developers that t() function is used for translating the strings to different languages. But many people don't know the purpose of Drupal.t() function which is used in a javascript file.

The other purpose of Drupal.t() is to replace the placeholders present in a string.

For example

var args = {};
args['!url'] = 'https://example.com';
args['%name'] = 'John Doe';
var foo = Drupal.t('%name is the owner of !url', args);
Here the %name is replaced with 'John Doe' and !url is replaced with the corresponding URL https://example.com.
 
Drupal.formatPlural()
 
Formatting plural strings are not something we often think about when it comes to translations. Plural forms are a part of the translation and something we need to consider. Drupal.formatPlural() is the counterpart to the PHP format_plural(). Drupal.formatPlural() works as same as PHP format_plural(). The arguments and return values of these two functions are similar.
 
For example:
var bar = Drupal.formatPlural(count, '@name has 1 site.', '@name has @count sites.', {'@name': John});
Here the output will be displayed as "John has 1 site" if the person has more than one site, it will display in plural form as "John has 2 sites" based on the value of "count" the first argument passed to formatPlural().
 
Hope this helps you to get a better understanding of usage of Drupal.t() and Drupal.formatPlural().
 
Get awesome tech content in your inbox