I18next namespace startup

I am using I18Next as a Javascript based translation solution, and here is what should happen:

  • The default namespace is loading "Core". It contains most of the keys that I want, but not all of them.
  • There is no fixed list of namespaces: therefore, I cannot just say i18n.init ns.namespace I want.
  • During pageload, optionally some β€œModules” are loaded into the Application, and they must also be translated. They must provide their i18n namespace name somewhere, and then i18n shuold make the namespace keys available.

Basically, is there a way for i18next to autoload namespaces as they are called? It is guaranteed that namespaces called through t("[SomeNamespace]Key.Key2"); are valid and certainly exist. The problem is that i18next cannot "autoload", and I cannot find a way to do a "manual" download of the resource file after i18n.init.

Here is my current code.

  $.i18n.init( { lng: "en", fallbackLng: "en", useCookie: false, resGetPath: "System/i18n/__ns__/__lng__.json", ns: "Core" }, function(t) { System.I18N = t; alert(System.I18N("LoginUI:Messages.Name")); } ); 

As expected, it just shows me LoginUI:Messages.Name instead of translating to System/i18n/LoginUI/en.json :

 { "Messages": { "Name": "Logon Interface" } } 

(Core / en.json does not matter in this case. All I need now is "LoginUI / en.json" for automatic download, or I can force manually download.)

+4
source share
2 answers

After some deepening in the source code, I created a solution that works, but certainly needs improvement in the long run.

In the definition of i18n.addjQueryFunct() add this to access resStore (translation storage variable):

 $.i18n._getResStore = _getResStore; $.i18n._writeResStore = _writeResStore; function _getResStore() { return resStore; } function _writeResStore(r) { resStore = r; } 

If you want to load the extra namespace, just do something like this:

 // define options, run $.i18n.init, etc... // suppose ns = "namespace_foobar_new" options.ns.namespaces.push(ns); $.i18n.sync._fetchOne(lang, ns, $.extend({}, $.i18n.options, options), function(err, data) { store = {}; store[lang] = {}; store[lang][ns] = data; newResStore = $.extend(true, {}, $.i18n._getResStore(), store); $.i18n._writeResStore(newResStore); }); 

Phew

+2
source

Now i18next now has a function to load additional namespaces after initialization: http://i18next.com/pages/doc_init.html#loadAdditionalNS

+3
source

Source: https://habr.com/ru/post/1443834/


All Articles