I18next: How can I change plural rule?

Created on 9 Aug 2016  Â·  4Comments  Â·  Source: i18next/i18next

I found that it could use i18next.pluralExtension.addRule before, but I got error now.
How can I set my plural rule?

For example,
JSON:
{
"number": "{{value}} count",
"number_plural": "{{value}} counts",
"number_plural_0": "no count"
}
Rule:
If value = 0, it will show "no count".
If value = 1, it will show "1 count".
If value > 1, it will show "N counts".

Most helpful comment

hm setting compatibilityJSON to 'v1' should be enough to keep old json format...

the function is here:
i18next.services.pluralResolver.addRule(lng, rule);

All 4 comments

addRule(lng, rule)

addRule('en', {
            "name": "English", 
            "numbers": [
                1,
                2
            ], 
            "plurals": function(n) { return Number(n != 1); }
        });

but why do you need to change a rule for a language...is it wrong?

seems your using a old version of i18next?!? the uptodate json format looks like http://i18next.com/docs/jsons/

what you want to solve is better handled by: http://i18next.com/translate/pluralInterval/

The rule is ok.
Because I have to keep old keys in json, I only upgrade i18next package to v3.3.1.

May I ask where addRule should bed added? Or is there a document for this function?

import I18Next from 'i18next/index';
import XHR from 'i18next-xhr-backend/index';

I18Next
    .use(XHR)
    .init({
        compatibilityJSON: 'v1',
        ...
    }, () => {
        ...
    });

I tried add addRule after I18Next, but I got error:
addRule is not a function(…)

Thank you for your help! :)

hm setting compatibilityJSON to 'v1' should be enough to keep old json format...

the function is here:
i18next.services.pluralResolver.addRule(lng, rule);

It seems zero's key in v1 doesn't have "_plural_0".
v1 JSON:

{
  "keyPluralMultipleEgArabic": "the plural form 0",
  "keyPluralMultipleEgArabic_plural_1": "the plural form 1",
  "keyPluralMultipleEgArabic_plural_2": "the plural form 2",
  ...
}

But my JSON: (zero's key has "_plural_")

{
  "number": "{{value}} count",
  "number_plural": "{{value}} counts",
  "number_plural_0": "no count"
}

So I have to adapt old key's rule by the addRule function.
I also referenced #316 and I found the solution:

i18next.services.pluralResolver.addRule(
        lng,
        {
            numbers: [0, 1, 'plural'],
            plurals: function plurals(n) {
                return Number(n >= 2 ? 2 : n);
            }
        });

Thanks for your help!
:)

Was this page helpful?
0 / 5 - 0 ratings