mrrau
Any recommendations or examples how to support plurals with this library?
#4 · closed · 2 comments
Any recommendations or examples how to support plurals with this library?
Hey, sorry for the delay! I managed to "unwatch" the repository somehow 🙈 If you don't want to manage the logic for plurality rules (who does?) I'd use [`Intl.PluralRules`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/select). I personally try to do this through functional definitions, but of course that's now always possible (JSON files, etc). So instead you can add nested keys for the different `select()` values to handle your variations, and use that as part of your `rosetta.t()` lookup: ```js const i18n = rosetta({ en: { warning: 'WARNING: {{message}}'', birds: { zero: 'birds', one: 'bird', two: 'two birds', few: 'some birds', many: 'flock of birds' } } }); const PR = new Intl.PluralRules(); function print(count) { let key = PR.select(count); let message = count ? i18n.t(`birds.${key}`) : 'Nevermind'; return i18n.t('warning', { message }); } print(0); // WARNING: Nevermind print(1); // WARNING: bird print(6); // WARNING: some birds print(42); // WARNING: flock of birds ``` Hope that helps~! Sorry again for the delay
@lukeed would you accept a PR that enables exactly that behavior with a flag? I think it's a very valuable and lightweight addition. ```js const i18n = rosetta({ en: { warning: 'WARNING: {{ birds }}'', birds: { zero: 'birds', one: 'bird', two: 'two birds', few: 'some birds', many: 'flock of birds' } } }); const t = i18n.plural('de-AT') t('warning', { birds: 2 }); // WARNING: two birds ```