Skip to content

Instantly share code, notes, and snippets.

@johnallers
Created March 25, 2012 01:29
Show Gist options
  • Select an option

  • Save johnallers/2190635 to your computer and use it in GitHub Desktop.

Select an option

Save johnallers/2190635 to your computer and use it in GitHub Desktop.
jQuery.localize with string supplanting
// sample application-en.json file
/*
{
Title : "Welcome to {CurrentSite}"
}
*/
if (typeof String.prototype.supplant === 'undefined') {
String.prototype.supplant = function (o, defaultIfMissing) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : (defaultIfMissing === undefined ? a : defaultIfMissing);
}
);
};
}
var settings = { CurrentSite = "my website" };
$("[rel*=localize]").localize("application", {
language: "en",
pathPrefix: "lang",
callback: function (data, defaultCallback) {
var applyFormatting = function (d) {
for (var key in d) {
var val = d[key];
if (typeof val === 'string') {
var formattedVal = val.supplant(settings, "");
d[key] = formattedVal;
} else if (typeof val === 'object') {
applyFormatting(d[key]);
}
}
};
applyFormatting(data);
defaultCallback(data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment