How to use i18next

Comprehensive i18next code examples:

How to use i18next.sync:

210
211
212
213
214
215
216
217
218
219

function loadResourcesForLanguage(lng) {
  return getI18nResourceStore(lng, i18next.options.ns.namespaces)
    .then(function(resStore) {
      // as of i18next-1.7.3, there is no api to do this so we edit the i18next object directly
      i18next.sync.resStore[lng] = resStore[lng];

      return resStore;
    });
}

How to use i18next.options:

207
208
209
210
211
212
213
214
215

  return deferred.promise;
};

function loadResourcesForLanguage(lng) {
  return getI18nResourceStore(lng, i18next.options.ns.namespaces)
    .then(function(resStore) {
      // as of i18next-1.7.3, there is no api to do this so we edit the i18next object directly
      i18next.sync.resStore[lng] = resStore[lng];

How to use i18next.addPostProcessor:

45
46
47
48
49
50
51
52
53
54
  var appLogger = { error: function () { return undefined; } };
  app.use(beans.get('handle404')(appLogger));
  app.use(beans.get('handle500')(appLogger));

  i18n.registerAppHelper(app);
  i18n.addPostProcessor('jade', function (val, key, opts) {
    return jade.compile(val, opts)();
  });
  return app;
}

How to use i18next.on:

43
44
45
46
47
48
49
50
51
52
    console.error(`Error loading i18n: ${err}`);
} else {
    console.log('i18n system loaded');
    const detectedLanguage = i18n.getMessage(`language_${getValidLocale("DEFAULT")}`);
    i18n.addResources({"detectedLanguage": detectedLanguage });
    i18next.on('languageChanged', function () {
        i18n.localizePage(true);
    });
}
if (cb !== undefined) {

How to use i18next.default:

43
44
45
46
47
48
49
50
51
52
this.mongooseClient = mongoose_1.default;
this.applyMiddleware();
this.routes();
this.connectDB();
// container.get<Subscribers>(TYPES.Subscribers)
i18next_1.default
    .use(i18next_fs_backend_1.default)
    .use(i18next_http_middleware_1.default.LanguageDetector)
    .init({
    backend: {

How to use i18next.serveWebTranslate:

149
150
151
152
153
154
155
156
157
158
    .serveDynamicResources(app)
    .serveChangeKeyRoute(app)
    .serveRemoveKeyRoute(app)
    .serveMissingKeyRoute(app);

  i18n.serveWebTranslate(app, option);

};

exports.disable = function() {

How to use i18next.exists:

124
125
126
127
128
129
130
131
132
133
i18n.getCurrentLocale = function() {
    return i18next.language;
};

i18n.existsMessage = function(key) {
    return i18next.exists(key);
};

/**
 * Helper functions, don't depend of the i18n framework

How to use i18next.addResourceBundle:

84
85
86
87
88
89
90
91
92
93
window.i18n = i18next
console.log('adding language', lang, json)

// for some reason, 'pt-br' was not working, use just pt instead
const k = lang.split('-')[0]
i18next.addResourceBundle(k, 'translation', json)

const languages = {}
updateAvailableLanguages()
emitter.emit('render')

How to use i18next.serveClientScript:

6
7
8
9
10
11
12
13
14
15
let Revision = require('./revision');

class Server {
  constructor() {
    this.app = express();
    i18n.serveClientScript(this.app)
      .serveDynamicResources(this.app);
    this.app.set('views', path.join(__dirname, 'vues'));
    this.app.set('view engine', 'jade');
    this.app.use(serveStatic(path.join(__dirname, 'public')));

How to use i18next.language:

120
121
122
123
124
125
126
127
128
129
i18n.getLanguagesAvailables = function() {
    return languagesAvailables;
};

i18n.getCurrentLocale = function() {
    return i18next.language;
};

i18n.existsMessage = function(key) {
    return i18next.exists(key);

How to use i18next.getFixedT:

40
41
42
43
44
45
46
                ns: namespaces,
                preload: languages,
        });

        require('../utils/Logger').ready(`${languages.length} language(s) have loaded. (${languages.join(', ')})`);
        return new Map(languages.map(item => [item, i18next.getFixedT(item)]));
};

How to use i18next.registerAppHelper:

27
28
29
30
31
32
33
    else
      console.log('i18n module initialized');
  });

  app.use(i18n.handle);
  i18n.registerAppHelper(app);
};

How to use i18next.dir:

607
608
609
610
611
612
613
614
615
616
617
618
619


    return report
  }


  static dir(locale) {
    return i18Next.dir(locale)
  }


}

How to use i18next.loadNamespaces:

56
57
58
59
60
61
62
63
64
65
        files.forEach(function(f) {
            if (fs.existsSync(path.join(dir,f,file))) {
                resourceMap[namespace].lngs.push(f);
            }
        });
        i18n.loadNamespaces(namespace,function() {
            resolve();
        });
    }
})

How to use i18next.createInstance:

73
74
75
76
77
78
79
80
81
82
// In case the default locale also has inadequate admin UI phrases
if (fallbackLng[0] !== 'en') {
  fallbackLng.push('en');
}
// Make sure we have our own instance to avoid conflicts with other apos objects
self.i18next = i18next.createInstance({
  fallbackLng,
  // Required to prevent the debugger from complaining
  languages: Object.keys(self.locales),
  // Added later, but required here

How to use i18next.use:

27
28
29
30
31
32
33
34
35
36
        loadPath: path.resolve(__dirname, '../languages/{{lng}}/{{ns}}.json'),
};

const { namespaces, languages } = await walkDirectory(path.resolve(__dirname, '../languages/'));

i18next.use(Backend);
await i18next.init({
        backend: options,
        debug: false,
        fallbackLng: 'en-US',

How to use i18next.changeLanguage:

82
83
84
85
86
87
88
89
90
91

i18n.changeLanguage = function(languageSelected) {
    if (typeof ConfigStorage !== 'undefined') {
        ConfigStorage.set({'userLanguageSelect': languageSelected});
    }
    i18next.changeLanguage(getValidLocale(languageSelected));
    i18n.selectedLanguage = languageSelected;
    console.log(i18n.getMessage('language_changed'));

};

How to use i18next.init:

28
29
30
31
32
33
34
35
36
37
};

const { namespaces, languages } = await walkDirectory(path.resolve(__dirname, '../languages/'));

i18next.use(Backend);
await i18next.init({
        backend: options,
        debug: false,
        fallbackLng: 'en-US',
        initImmediate: false,

How to use i18next.t:

8
9
10
11
12
13
14
15
16
17
validate(val, msg, arg) {
        const lng = msg.client.translator.resolveLanguage(msg);
        const int = Number.parseInt(val);
        if(Number.isNaN(int)) return false;
        if(arg.oneOf && !arg.oneOf.includes(int)) {
                return i18next.t('argument_type.integer.available_options', {
                        lng,
                        options: arg.oneOf.map(opt => `\`${opt}\``)
                                .join(', ')
                });