Skip to content
This repository has been archived by the owner on Apr 18, 2023. It is now read-only.

Commit

Permalink
Add support for automatically choosing different i18n keys for differ…
Browse files Browse the repository at this point in the history
…ent countries

Example: if countryCode is set to RU then lookup keys in order: <key>.RU, <key>.default, <key>
  • Loading branch information
inez committed Apr 11, 2017
1 parent 6108623 commit 307774d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
19 changes: 18 additions & 1 deletion addon/services/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ export default Parent.extend(Evented, {
// The user's locale.
locale: null,

// @public
countryCode: Ember.computed({
set(key, value) {
if(Ember.isBlank(value) || value.length !== 2 || value !== value.toUpperCase()) {
throw new Error('Invalid countryCode, expected a two-character uppercase string e.g. "US"');
}
this.set('_countryCode', value);
return value;
}
}),

// @public
// A list of found locales.
locales: computed(getLocales),
Expand All @@ -36,8 +47,14 @@ export default Parent.extend(Evented, {
const count = get(data, 'count');

const defaults = makeArray(get(data, 'default'));
const countryCode = this.get('_countryCode');

if (defaults.length === 0 && Ember.isPresent(countryCode)) {
defaults.push(`${key}.${countryCode}`, `${key}.default`, key);
} else {
defaults.unshift(key);
}

defaults.unshift(key);
const template = locale.getCompiledTemplate(defaults, count);

if (template._isMissing) {
Expand Down
5 changes: 4 additions & 1 deletion tests/dummy/app/locales/en/translations.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@ export default {
'pluralized.translation': {
one: 'One Click',
other: '{{count}} Clicks'
}
},

'default1.US': 'default1.US',
'default2.default': 'default2.default'
};
8 changes: 8 additions & 0 deletions tests/unit/i18n-t-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,11 @@ test("check unknown locale", function(assert) {
const result = this.subject({ locale: 'uy' }).t('not.yet.translated', {count: 2});
assert.equal('Missing translation: not.yet.translated', result);
});

test('inez', function(assert) {
const i18n = this.subject({ locale: 'en' });
run(i18n, 'set', 'countryCode', 'US');

assert.equal('' + i18n.t('default1'), 'default1.US');
assert.equal('' + i18n.t('default2'), 'default2.default');
});

0 comments on commit 307774d

Please sign in to comment.