How to expose dynamic translatable text to translation tools like poedit

The gettext translation framework is the best I ever used. All you have to do in order to find out which strings in your code require translation, and to create a skeleton translation file, is to have a function which performance the actual translation and just keep calling it for each translatable string. Then automated tool like poedit can be configured to parse your code, find all the strings that are used as parameter to the function and make a skeleton file containing them.
If our translation function is __() then when poedit parses our code and finds __(‘Somthing’) it generates a file in format similar to

Original "Something"
Translation ""

Now we just need to fill the translation (and you don’t need to be a coder to do that!) and tell our code to look for translations in this file.

Dynamic text breaks this nice system as almost by definition dynamic means that we don’t know the exact value at “compilation” time.When poedit scans the code below it doesn’t find any translatable strings.

a = get_response_from_remote_server(random-value);
print(__(a));

But many times we know in advance that get_response_from_remote_server() can return only a limited set of strings, for example only “apple” and “orange”. Right now in order for them to be translated correctly we will need to add them manually to the translation file, which makes it much harder to maintain as you will need to add them again after the next time poedit will process your code.

Luckily there is a way to maintain the list of that kind of string asĀ  part of the code in a way which enable poedit to detect them – just put them in the code.

dummy = __('Apple');
dummy = __('Orange');
a = get_response_from_remote_server(random-value);
print(__(a));

Dummy here is never used, so there are no side affects. The problem with this approach is that we waste CPU time to call a function while we don’t need the value it returns.

Obvious improvement will be

if (false) {
  dummy = __('Apple');
  dummy = __('Orange');
}
a = get_response_from_remote_server(random-value);
print(__(a));

Now we don’t execute the functions and a compiler might even simply discard that section of the code resulting with zero impact on performance while maintaning the ability to generate translation file automatically.

Which leads to the best option – add a source code file which include the strings but don’t add it to your compilation chain in your make file or don’t include it.

dummy = __('Apple');
dummy = __('Orange');

Nirvana.

Leave a Reply

Your email address will not be published. Required fields are marked *