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:
<br />function(){<br />  var mytext = _( "there are %num%%% of %red% %apples%", { num:12, red:'yellow', apples:'bananas' } );<br />};<br />
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.
<br /><br />// implementation of gettext functions<br /><br />// function to parse strings<br />// returns substituted string with args<br />// string written in form: 'there are %num%%% of %red% %apples%'<br />// argse are object { num:'12', red:'yellow', apples:'bananas' }<br />// return will be 'there are 12% of yellow bananas'<br />// when translated as '%red% %apples% on kastis %num%%%'<br />// and the arguments are { num:'12', red:'kollaseid', apples:'banaane' }<br />// then the return will be 'kollaseid banaane on kastis 12%'<br />//<br />function my_gettext_parse( string, args_obj )<br />{<br />	var result = '';<br />	var token = '';<br />	var i,n=string.length;<br />	var out_of_token = true;<br />	for( i=0; i<n; i++ )<br />	{<br />		if( out_of_token )<br />		{<br />			if( string[i] == '%' && string[i+1] != '%' )<br />			{<br />				//start of token<br />				token = '';<br />				out_of_token = false;<br />			}<br />			else<br />			{<br />				result += string[i];<br />				if( string[i] == '%' && string[i+1] == '%' )<br />					i++;<br />			}<br />		}<br />		else<br />		{<br />			// inside token<br />			if( string[i] == '%' )<br />			{<br />				out_of_token = true;<br />				// substitute the result<br />				result += args_obj[token];<br />			}<br />			else<br />			{<br />				token += string[i];<br />			}<br />		}<br />	}<br />	return result;<br />}<br /><br />// TODO: this is stub<br />function _( arg, args_obj )<br />{<br />	return my_gettext_parse(arg, args_obj);<br />}<br /><br />//TODO: this is stub<br />function _p( num, singular, plural, args_obj )<br />{<br />	if( num == 1 )<br />		return my_gettext_parse(singular, args_obj);<br />	return my_gettext_parse(plural, args_obj);<br />}<br /><br />


  • 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.