Wednesday, August 26, 2009

Extending JQuery Translate plugin to include raw text translations

There is an excellent JQuery plugin to translate text. This is based on Google Ajax Language API. This JQuery based translate plugin circumvents the limitation of number of characters that can be sent using the raw Language API. This is a serious limitation when integrating language API into our code, we cannot translate big documents typically having 2000 or more characters.

The translate plugin works very well, except there is a minor limitation, i.e. when we pass a raw text to it (which may contain line breaks, tabs and other special characters), the translated text strips out such characters back. Many times we need to preserve these in the translated text too.

The reason for this is because in the plugin, the language translate API is called using:

google.language.translate(text|content, srcLang, destLang, callback)
It always passes default text which the API interprets it as HTML markup. To pass a raw text, one needs to pass a content object with attributes {text: textToTranslate, type:'text'}. This way the google language API treats it as raw text and preserves the line breaks and other special characters.

So in order to have the jquery translate plugin work same way for raw texts also, I have extended the plugin to make distinction between type of the text to translate. One can pass the type in options.
Default is: type: 'html' and for text one would need to pass type: 'text'.
jQuery.translate(textToTranslate, languageToCode, {
type: 'text',
complete: function(translation){
//translation contains the complete translation of textToTranslate
error: function(){
//error callback

So I have extended the plugin to take care of calling google language API based on type. I have called this version as 1.3.10. It should work with jQuery 1.2+

Hope you find this useful. Any questions or comments feel free to contact me.


ps: download the above version from this link.

No comments: