2

How can I make i18next load all languages from just one file?

I managed to do it by putting each language in a seperate file (translation-en.json, translation-no.json, etc), and also managed to input languages with the resStore option, but putting it all in a seperate .json file is really not documented anywhere (I've searched for 4 hours+ now)

My js code:

i18n.init({
    debug: true,
    lng: 'en',
    resGetPath: 'translation.json'
},
function(t) {
    console.log(t('test'));
});

My translation.json file:

{
    en: { 
        translation: {
            test: "some string"
        }
    },
    no: { 
        translation: {
            test: "litt tekst"
        }
    }
}

Ok, so I managed to "hack" it byt putting an object into a seperate .js file, include it in a script tag and loading it using resStore, but that just can't be the best way to use this lib.

4

1 回答 1

2

假设您translation.json已加载并分配给名为 的变量resStore

var resStore = {
    en: { 
        translation: {
            test: "some string"
        }
    },
    no: { 
        translation: {
            test: "litt tekst"
        }
    }
};

接下来,您可以使用您的函数覆盖默认的 ajax 加载customLoad功能。一个示例可能如下所示:

var options = {
    lng: 'en',
    load: 'current',
    lowerCaseLng: true,
    fallbackLng: false,
    resGetPath: 'i18n/__lng__/__ns__.json',
    customLoad: function(lng, ns, options, loadComplete) {
        var data = resStore[lng][ns];
        loadComplete(null, data); // or loadComplete('some error'); if failed
    },
    ns: {
        namespaces: ['translation'],
        defaultNs: 'translation'
    }
};
i18n.init(options, function(t) {
    t('test'); // will get "some string"
});

2015 年 3 月 20 日的新更新

您可以使用以下选项简单地传递您的资源存储resStore

i18n.init({ resStore: resources });
于 2015-03-18T15:59:12.553 回答