Skip to main content
Translatable strings

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 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 counter part 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 javascript file. 

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

For example

var args = {};
args['!url'] = 'http://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 http://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 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(). Arguments and return value 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 sites, it will display in plural form as "John has 2 sites" based on the value of "count" the first argument passedto formatPlural(). 
 
Hope this helps you to get better understanding on usage of Drupal.t() and Drupal.formatPlural(). 
 

Comments

All this information directly impacts the future of your venture.
The benefit of the intelligence provided by the adviser can only be fully appreciated when it has been delivered and understood
by the recipient. Make a list of the tasks for each day and cross them out when done.