Skip to content
Snippets Groups Projects
Commit 9340251a authored by Lloyd Hilaiel's avatar Lloyd Hilaiel
Browse files

make the format() function for l10n more ergonomic - don't require a third argument

parent 6a81e328
No related branches found
No related tags found
No related merge requests found
......@@ -251,15 +251,17 @@ exports.languageFrom = function (locale) {
* of values for positional replacement.
*
* Named Example:
* format("%(salutation)s %(place)s", {salutation: "Hello", place: "World"}, true);
* format("%(salutation)s %(place)s", {salutation: "Hello", place: "World"});
* Positional Example:
* format("%s %s", ["Hello", "World"]);
*/
var format = exports.format = function (fmt, obj, named) {
if (! fmt) return "";
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
if (!fmt) return "";
if (Array.isArray(obj) || named === false) {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
} else if (typeof obj === 'object' || named === true) {
return fmt.replace(/%\(\s*([^)]+)\s*\)/g, function(m, v){
return String(obj[v]);
});
}
};
......@@ -20,14 +20,16 @@
},
// See lib/i18n.js format docs
format: function (fmt, obj, named) {
if (! fmt) return "";
if (! fmt.replace) {
if (!fmt) return "";
if (!fmt.replace) {
return fmt;
}
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
if (_.isArray(obj) || named === false) {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
} else if (_.isObject(obj) || named === true) {
return fmt.replace(/%\(\s*([^)]+)\s*\)/g, function(m, v){
return String(obj[v]);
});
}
}
};
......@@ -40,5 +42,4 @@
var gt = new Gettext(params);
window.gettext = gt.gettext.bind(gt);
window.format = gt.format.bind(gt);
}());
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment