Using GNU gettext with Enyo.

I see that there is not much of work made for using GNU gettext for javascript. The gettext system is pretty powerful for translation of applications. Although javascript makes the string replacements simple, there are many translation specific issues and tools aside of it. I post this message in order somebody will find it helpful and finds the need to develop it further.

I have written few little functions for addressing the task in javascript. The translatable string can be written like this:

function(){
var mytext = _( "there are %num%%% of %red% %apples%", { num:12, red:'yellow', apples:'bananas' } );
};
The gettext tools are making pretty good job to find all the translatable strings and to manage the changes.

The translation function is pretty simple, note that in the following sample the translatable string is not translated. It is needed to be done in the _() functions.


// implementation of gettext functions

// function to parse strings
// returns substituted string with args
// string written in form: 'there are %num%%% of %red% %apples%'
// argse are object { num:'12', red:'yellow', apples:'bananas' }
// return will be 'there are 12% of yellow bananas'
// when translated as '%red% %apples% on kastis %num%%%'
// and the arguments are { num:'12', red:'kollaseid', apples:'banaane' }
// then the return will be 'kollaseid banaane on kastis 12%'
//
function my_gettext_parse( string, args_obj )
{
var result = '';
var token = '';
var i,n=string.length;
var out_of_token = true;
for( i=0; i<n; i++ )
{
if( out_of_token )
{
if( string[i] == '%' && string[i+1] != '%' )
{
//start of token
token = '';
out_of_token = false;
}
else
{
result += string[i];
if( string[i] == '%' && string[i+1] == '%' )
i++;
}
}
else
{
// inside token
if( string[i] == '%' )
{
out_of_token = true;
// substitute the result
result += args_obj[token];
}
else
{
token += string[i];
}
}
}
return result;
}

// TODO: this is stub
function _( arg, args_obj )
{
return my_gettext_parse(arg, args_obj);
}

//TODO: this is stub
function _p( num, singular, plural, args_obj )
{
if( num == 1 )
return my_gettext_parse(singular, args_obj);
return my_gettext_parse(plural, args_obj);
}

Comments

  • Thanks for sharing. Enyo apps have traditionally used either g11n (for the older ones) or enyo-ilib but both are somewhat weighty if all you need is string replacement/formatting.
Sign In or Register to comment.