Posted on

Translating JavaScript WebApp with GetText

GNU GetText is very powerful tool for translation of applications. Entire Linux world is using it. The tool-set includes original text changes tracking, automatic translations and more. Several user interfaces are available to make translation work faster. Programmers have very solid and understandable way to write original texts into code like this:

{
  the_need: _("I want an red apple")
}

The tools will collect this into translation intermediate file looking for the special function _() from the code with translatable strings. The intermediate file is text file and looks like this:

#: ../source/app_account.js:15
msgid "I want an red apple"
msgstr ""

where msgid is the original text and msgstr is translated string. GetText for C/C++ and other compiled languages is going to order the msgid text in ascending order so that the translation can be found using binary search algorithm and is taking least possible time.

When we look from the application perspective, then the “red apple” might be something that is computed and inserted into the text. In C language it would be done like this:

void do_something_with( char *color, char *item )
{
  char result[200];
  snprintf( result, 200, _("I want an %1$s %2$s"), color, item );
  // ...
}

where color and  item are string pointers to the actual texts. Those items need to be translated outside the function. Those may be originated from database where database needs to handle different translations inside. Note that not all C printf function implementations support reordering of the arguments using “%m$s”, where m is the argument order number.

On JavaScript application we can write the above like this:

{
  the_need: _("I want an %red% %apple%",{red:color, apple:item})
}

afterwards when the variable color holds “green” and item holds “onion” the resulting message would be “I want an green onion”. The translatable message in translation file will look like this:

#: ../source/app_account.js:15
msgid "I want an %red% %apple%"
msgstr "Quiero una %apple% %red%"

You see that the msgid is holding these human understandable placeholders for JavaScript message translator. Also, you will see how the translator would reorder the red and apple placeholders for the Spanish language. Thus if the variable color holds “roja” and variable item holds “manzana” then the Spanish translation will be “Quiero una manzana roja”.

I have not seen that the GetText has been used with JavaScript so far. We have used it. The system is pretty straight forward with JavaScript as the language provides lots of operators for it. If you want to know more about how to use GetText with JavaScript application and get an implementation, then please contact us.