How to change dojo locale after dojo loaded?

2019-06-14 01:57发布

问题:

We need set locale in data-dojo-config before dojo loaded so that dojo.i18n will work with this locale. Is there any workaround that we can change this locale in dojo/_base/config after dojo loaded so that any further dojo.i18n call will work with this new locale?

I have a single page application, by carefully design, I already be able to recreate all my UI widgets dynamically anytime. I want to add a Select somewhere so that user can change languages on the fly. Currently the only solution I have is put a queryString locale='newLocale' at Url and force browser refresh. That works but everything User have done lost and with a fresh start. That's not what I want.

Any idea? I don't afraid some changes of dojo to make this happen since my application will be built as a single layer and deploy to customers.

回答1:

According to dojo's documentation, you cannot change the locale once it's loaded. See this page from their documentation, the relevant line is:

Once Dojo is loaded, it is not possible to change the locale for the page.

Your description of adding a new parameter is what I've done in this situation, you can specify the locale property on the dojoConfig object to override the default locale.


EDIT: There is an open bug for this use case, see https://bugs.dojotoolkit.org/ticket/17196. In that ticket there also appears to be a workaround that basically involves manually loading the resource file of the language you want to use and updating any text.

So, adapting their example (http://jsbin.com/aquviq/1/edit), this would run after you initiate a change locale action:

require(['dojo/i18n!dojo/nls/' + resourceModuleWithLocale], function (resource) {
    /* in here, you must set all of the text manually to the values in the resource object */
});

It still seems like a lot of work, but I suppose that's one possible way to accomplish this.