Skip to content

Instantly share code, notes, and snippets.

@kmdavis
Created February 11, 2010 00:46
Show Gist options
  • Save kmdavis/301049 to your computer and use it in GitHub Desktop.
Save kmdavis/301049 to your computer and use it in GitHub Desktop.
jQuery i18n getText plugin
// requires jQuery for $.makeArray and $.extend
(function ($) {
var data = {}, cacheMisses = false, loadedUrls = [];
$.gt = function (string) {
if (data.hasOwnProperty(string)) {
string = data[string];
} else if (false !== cacheMisses) {
if (!cacheMisses.hasOwnProperty(string)) {
cacheMisses[string] = 0;
}
cacheMisses[string] += 1;
}
if (1 < arguments.length) {
var args = $.makeArray(arguments), key;
if (2 === args.length && args[1] instanceof Object) {
args = args[1];
} else {
args.splice(0, 1);
}
for (key in args) {
if (args.hasOwnProperty(key)) {
string = string.replace(new RegExp("\\{" + key + "\\}", "g"), args[key]);
}
}
}
return string;
};
$.gt.load = function (translations, callback) {
if (translations instanceof Object) {
$.extend(data, translations);
if (callback) {
callback();
}
} else if ("string" == typeof translations) {
if ($.inArray(translations, loadedUrls)) {
if (callback) {
callback();
}
} else {
$.getJSON(translations, function(response) {
$.extend(data, response);
if (callback) {
callback();
}
});
}
}
};
$.gt.logCacheMisses = function() {
cacheMisses = {};
};
$.gt.cacheMisses = function () {
return cacheMisses;
};
$.fn.gt = function() {
$.each(this, function() {
$(this).html($.gt($(this).html()));
});
};
}(jQuery));
// Simple Tests:
$.gt.load({
"simple test": "fail",
"test template": "hello {name}",
"another test" : "{0} + {1} = {2}"
});
$.gt.load({
"simple test": "pass"
}, function() {
if (console) {
console.group("testing $.gt");
if ("pass" !== $.gt("simple test")) {
console.debug("simple test failed");
}
if ("hello world" !== $.gt("test template", {name: "world"})) {
console.debug("template test #1 failed");
}
if ("3 + 2 = 5" !== $.gt("another test", 3, 2, 5)) {
console.debug("template test #2 failed");
}
$.gt.logCacheMisses();
if ("cache miss" !== $.gt("cache miss")) {
console.debug("cache miss test failed");
}
if (1 !== $.gt.cacheMisses()["cache miss"]) {
console.debug("cache miss logging test failed");
}
// no portable test for the url load code paths
console.groupEnd("testing $.gt");
}
})
//$.gt.load("/locale/en-US");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment