DEV: add translation fallback option for i18n

Allow for a default translation string to be returned when a translation cannot
be found.

Useful in contexts where there is a known fallback, such as custom emoji group
strings.
This commit is contained in:
Jeff Wong 2022-06-07 12:02:09 -07:00
parent 532935043c
commit 9a656e18e9
2 changed files with 34 additions and 24 deletions

View File

@ -279,4 +279,13 @@ module("Unit | Utility | i18n", function (hooks) {
"Hi $& $&" "Hi $& $&"
); );
}); });
test("Customized missing translation string", function (assert) {
assert.strictEqual(
I18n.t("emoji_picker.customtest", {
translatedFallback: "customtest",
}),
"customtest"
);
});
}); });

View File

@ -8,7 +8,7 @@ I18n.defaultLocale = "en";
I18n.pluralizationRules = { I18n.pluralizationRules = {
en(n) { en(n) {
return n === 0 ? ["zero", "none", "other"] : n === 1 ? "one" : "other"; return n === 0 ? ["zero", "none", "other"] : n === 1 ? "one" : "other";
} },
}; };
// Set current locale to null // Set current locale to null
@ -168,7 +168,10 @@ I18n.translate = function(scope, options) {
try { try {
return this.interpolate(translation, options); return this.interpolate(translation, options);
} catch (error) { } catch (error) {
return this.missingTranslation(scope, null, options); return (
options.translatedFallback ||
this.missingTranslation(scope, null, options)
);
} }
}; };
@ -187,13 +190,11 @@ I18n.toNumber = function(number, options) {
precision: 3, precision: 3,
separator: this.SEPARATOR, separator: this.SEPARATOR,
delimiter: ",", delimiter: ",",
strip_insignificant_zeros: false strip_insignificant_zeros: false,
}); });
var negative = number < 0, var negative = number < 0,
string = Math.abs(number) string = Math.abs(number).toFixed(options.precision).toString(),
.toFixed(options.precision)
.toString(),
parts = string.split(this.SEPARATOR), parts = string.split(this.SEPARATOR),
buffer = [], buffer = [],
formattedNumber; formattedNumber;
@ -219,7 +220,7 @@ I18n.toNumber = function(number, options) {
if (options.strip_insignificant_zeros) { if (options.strip_insignificant_zeros) {
var regex = { var regex = {
separator: new RegExp(options.separator.replace(/\./, "\\.") + "$"), separator: new RegExp(options.separator.replace(/\./, "\\.") + "$"),
zeros: /0+$/ zeros: /0+$/,
}; };
formattedNumber = formattedNumber formattedNumber = formattedNumber
@ -256,7 +257,7 @@ I18n.toHumanSize = function(number, options) {
options = this.prepareOptions(options, { options = this.prepareOptions(options, {
precision: precision, precision: precision,
format: this.t("number.human.storage_units.format"), format: this.t("number.human.storage_units.format"),
delimiter: "" delimiter: "",
}); });
number = this.toNumber(size, options); number = this.toNumber(size, options);