Setting RequireJS i18n locale dynamically

后端 未结 2 2094
庸人自扰
庸人自扰 2021-02-06 09:45

I am using the RequireJS i18n plugin to load translations into my application. I\'m struggling with the concept of runtime determination of a user\'s preferred language<

2条回答
  •  孤独总比滥情好
    2021-02-06 10:09

    It seems after a lot of research, the best approach for solving this problem is to check localStorage for a locale value. If this hasn't been set yet, I load the application using a dummy language:

    var locale = localStorage.getItem('locale') || 'dummy';
    
    require.config({
        config: {
            i18n: {
                locale: locale
            }
        }
    });
    
    require(['app']);
    

    I use a language called dummy, set to an empty object in my nls file. Using a dummy, rather than a default, means I don't have to guess what the user's language might be, and potentially force them to download a whole load of translations in the wrong language:

    define({
        "root": false,
        "dummy": {}, //dummy language with no translations if user language is unknown
        "fr": true,
        "en": true,
        "en-uk": true,
        "fr-fr": true
    });
    

    Then, when the app has loaded and the user has been logged in, I query the database using a service call, set the language in localStorage and reload the app using location.reload():

        //retrieve user object (including preferred locale) from service call
        user = getUserObject(userId); 
    
        locale = localStorage.getItem('locale');
    
        if (!locale || locale !== user.locale) {
    
            localStorage.setItem('locale', user.locale);
    
            //reload the app
            location.reload();
        }
    

    Of course, I need to support old version of IE so I have also included fallbacks using userData, but this is the gist of the solution.

    This approach is partially taken from how the guys at RESThub do it.

提交回复
热议问题