Created
June 16, 2011 23:55
-
-
Save kingcu/1030604 to your computer and use it in GitHub Desktop.
Handy Ruby I18n style javascript interpolation class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Translations = { | |
translations: {}, | |
load: function(trans) { | |
this.translations = this.translations || {}; | |
for(attr in trans) { this.translations[attr] = trans[attr] } | |
}, | |
t: function(key, interp) { | |
var t = this.translations[key]; | |
if(interp === undefined) return t; | |
if(typeof t == "string") return this.interpolate(t, interp); | |
if(typeof t == "object" && interp && interp.count !== undefined) { | |
//nested object, so it's a plural key with zero|one|other keys... | |
//this is kinda a ghetto assumption, but it's easy | |
if(interp.count == 0 && t.zero) return this.interpolate(t.zero, interp); | |
else if(interp.count == 1) return this.interpolate(t.one, interp); | |
else return this.interpolate(t.other, interp); | |
} | |
return key; | |
}, | |
interpolate: function(str, obj) { | |
return str.replace(/%{([^%{}]*)}/g, | |
function (a, b) { | |
var r = obj[b]; | |
return typeof r === 'string' || typeof r === 'number' ? r : a; | |
} | |
); | |
}, | |
needsPlural: function(options) { | |
//relies on checking for interpolation key 'count' - won't work | |
//if the interpolation key is anything else...kinda ghetto | |
return (options.count && typeof options.count != 'string' && options.count > 1); | |
} | |
} | |
T = Translations; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment