56 lines
2.0 KiB
JavaScript
56 lines
2.0 KiB
JavaScript
// Browser-side translations. The server prints the catalog for the current
|
|
// language (translations/js.<locale>.yaml, via the vindn_i18n_json Twig
|
|
// function in base.html.twig) into window.VINDN_I18N; this module only looks
|
|
// things up. All visible text in public/js goes through t()/count() so a new
|
|
// language is a translations/ change, not a code change.
|
|
(function (window) {
|
|
var data = window.VINDN_I18N || {};
|
|
var locale = data.locale || 'de';
|
|
var messages = data.messages || {};
|
|
|
|
var numberFormats = {};
|
|
var pluralRules;
|
|
try {
|
|
pluralRules = new Intl.PluralRules(locale);
|
|
} catch (e) { /* unknown locale tag — fall back to "other" below */ }
|
|
|
|
// "Hello %name%" + {name: 'x'} — same %placeholder% syntax as Symfony's
|
|
// catalogs. An unknown key shows itself, which is visible but harmless.
|
|
function t(key, params) {
|
|
var text = Object.prototype.hasOwnProperty.call(messages, key) ? messages[key] : key;
|
|
if (params) {
|
|
Object.keys(params).forEach(function (name) {
|
|
text = text.split('%' + name + '%').join(params[name]);
|
|
});
|
|
}
|
|
return text;
|
|
}
|
|
|
|
// Number in the page language, at most `decimals` fraction digits.
|
|
function number(value, decimals) {
|
|
decimals = decimals || 0;
|
|
if (!numberFormats[decimals]) {
|
|
numberFormats[decimals] = new Intl.NumberFormat(locale, { maximumFractionDigits: decimals });
|
|
}
|
|
return numberFormats[decimals].format(value);
|
|
}
|
|
|
|
// Plural-aware message: looks up "<key>.<rule>" (one, other, few, …) for
|
|
// the language's own plural rules, falling back to "<key>.other". The
|
|
// count itself is available as %n%, already formatted.
|
|
function count(key, n, params) {
|
|
var rule = pluralRules ? pluralRules.select(n) : 'other';
|
|
var full = key + '.' + rule;
|
|
if (!Object.prototype.hasOwnProperty.call(messages, full)) full = key + '.other';
|
|
return t(full, Object.assign({ n: number(n) }, params || {}));
|
|
}
|
|
|
|
window.VindnI18n = {
|
|
locale: locale,
|
|
dateFormat: data.dateFormat || 'd.m.Y',
|
|
t: t,
|
|
number: number,
|
|
count: count
|
|
};
|
|
})(window);
|