Skip to content

Instantly share code, notes, and snippets.

@klederson
Last active December 16, 2015 14:19
Show Gist options
  • Save klederson/5447783 to your computer and use it in GitHub Desktop.
Save klederson/5447783 to your computer and use it in GitHub Desktop.
This gist demonstrate how easly integrate Gettext.js + jQuery in a smart/automatized way to translate entire sites by using some ".po" file.
/**
* This is a experimental and fun script/tutorial that demonstrates how to translate sites USING Gettext
* without use _() stuff ( or others ) in your html just by parsing all your html visible text.
*
* @author Klederson Bueno <klederson@phpburn.com>
* @see http://jsgettext.berlios.de/doc/html/Gettext.html
* @see http://www.phpburn.com/
* @version 0.1a
*/
var iFindTranslator = {
t : null,
/**
* This method will perform the translation of a given container ( can be used into body element for example )
* This will get your already implemented PO file (references bellow) and use it to translate.
*
* YES I KNOW WE CAN SETUP DOMAINS AND STUFF IN HERE but remember this is just an ilustrative tutorial do all
* the fancy stuff you want to this is just to make things work.
*
* @see http://jsgettext.berlios.de/doc/html/Gettext.html
*/
translate : function(container) {
//this way will help you to save memory instead of keep creating everytime you call the translate method
var t = this.t == null ? new Gettext() : this.t; //this assumes that you already loaded the right lang/PO file
$(container).find("*").contents().filter(function () {
if ( this.nodeType == 3) {
if((this.nodeValue.toString().trim() != "")) {
var id = this.nodeValue.toString().trim();
this.nodeValue = this.nodeValue.replace(id,t.gettext(id)); //this will help you to preserve spaces
}
}
});
},
/**
* This method will help you to extract text from the current screen and generate the PO file
* You'll need to copy the console output and create your .PO file
*/
lazyExtractor : function(container) {
$(container).find("*:visible").contents().filter(function () { //we only extract visible stuff so be sure of this
if ( this.nodeType == 3) {
if((this.nodeValue.toString().trim() != "")) {
var value = this.nodeValue.toString().trim();
console.log('msgid "' + value + '"');
console.log('msgstr "TRANSLATED: ' + value + '"');
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment