How to switch languages with the i18next plugin?
Asked Answered
T

2

18

I am using Backbone.js in my application and the i18next plugin for my language switch function on my application. When I pass a value to the lng option in the init function call, then it translates my page correctly.

Now I want to do this dynamically via a language selector. I have a <select> of four languages and I want to pass the value of the selected language to the lng option of the init function.

Here is my code:

HTML

<div class="col-xs-6>
    <select class="form-control language-selector">
        <option value="de">Deutsch</option>
        <option value="en">English</option>
        <option value="fr">Français</option>
        <option value="it">Italiano</option>
    </select>
</div>

JavaScript

i18next.init({
        debug: true,
        languages: ['de','en','fr','it'],
        lng: 'de',  
        fallbackLng: false,
        load: 'current',
        resources: resBundle
    }, function(err, t){

});

'change .language-selector': function(e){
    e.preventDefault();
    i18next.setLng($(e.target).val(), (err, t) => {
        console.log(arguments);
        this.render();
    });
}
Travis answered 7/12, 2016 at 10:17 Comment(4)
have you tried to print your i18n model after changin the language to see if is not a problem with your setLng? if the model is really getting the language changed?Jannet
@rule: I get an error "i18next.setLng" is not a function.Travis
check if i18next is initialized .. do console in callback function of init.Painful
@SunilBN: Yes, when I load the application then i18next. init() function is initialized but when I change the language via select then it gives me error i18next.setLng is not a function.Travis
C
18

The function to change the language is i18next.changeLanguage. You only need to call it, there's no need to call init again or to "change the init options" as the options are attributes inside i18next and they are managed through the API (the functions).

i18next.init({
    lng: 'en',
    fallbackLng: ['en', 'de', 'fr', 'it'],
});

// catch the event and make changes accordingly
i18next.on('languageChanged', (lng) => {
    // E.g. set the moment locale with the current language
    moment.locale(lng);

    // then re-render your app
    app.render();
});

In the view with the language selector:

const LangView = Backbone.View.extend({
    events: {
        'change .language-selector': 'onLangChange',
    },

    onLangChange(e) {
        // only change the language
        i18next.changeLanguage(e.currentTarget.value);
    }
});

Proof of concept

const app = {};

app.translations = {
    "fr": {
        "translation": {
            "label": "Choisir une langue",
            "fr": "Français",
            "en": "Anglais"
        }
    },
    "en": {
        "translation": {
            "label": "Choose a language",
            "fr": "French",
            "en": "English"
        }
    }
};

i18next.init({
    lng: 'en',
    fallbackLng: ['en', 'fr'],
    resources: app.translations,
});

// catch the event and make changes accordingly
i18next.on('languageChanged', (lng) => {

    // then re-render your app
    app.view.render();
});

const LangView = Backbone.View.extend({
    template: _.template($('#selector').html()),
    langTemplate: _.template('<option value="<%= value %>"><%= name %></option>'),
    events: {
        'change .language-selector': 'onLangChange',
    },

    render() {
        this.$el.html(this.template({
            label: i18next.t('label')
        }));
      
        // cache the jQuery object of the select
        this.$selector = this.$('.language-selector');
      
        // then dynamically populate it
        this.populateSelector();

        return this;
    },

    populateSelector() {
        // for each languages in i18next, add an option to the select
        _.each(i18next.languages, this.addLanguage, this);
    },

    addLanguage(lang) {
        // adding the option with the translated names
        this.$selector.append(this.langTemplate({
            value: lang,
            name: i18next.t(lang),
        }));
    },

    onLangChange(e) {
        // change the language
        i18next.changeLanguage(e.currentTarget.value);
    }
});

app.view = new LangView();

$('#app').html(app.view.render().el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next/4.1.1/i18next.min.js"></script>

    <div id="app"></div>
    <script type="text/template" id="selector">
        <label>
            <%=label %>
          </label>
        <select class="form-control language-selector"></select>
    </script>

Regarding translating the language names, take a look at Language of language names in the language selector?

Cutwork answered 7/12, 2016 at 15:23 Comment(5)
@Travis yes, I corrected that. I have a service module named i18n in my app which is i18next in the background and forgot to change the name back.Cutwork
I dont use moment.locale in my view. What is the alternative of that.?Travis
@Travis that is just an example of stuff to handle there, you can completely ignore moment.Cutwork
Ok, but still I get an error."cannot read property 'render' of undefined" I defined .on method after the .init method, and both are in initialize function. I am confused that why this.render(); is not working in my i18next.on method.Travis
Of-course I understand what I am doing..;) and I already found out what the problem was. I am calling another API in initialization and it needs also the lang parameter. That's why it wasn't working. I need to figure out that. But as per this question your solution is working good. Thank you for that.Travis
P
1
$(document).ready(function () {
    i18n.init({
        "lng": 'en',
        "resStore": resources,
        "fallbackLng" : 'en'
    }, function (t) {
        $(document).i18n();
    });

   'change .language-selector': function(e){
        e.preventDefault();
        i18n.init({
        lng: $(e.target).val()}, (err, t) => {
            console.log(arguments);
            $(document).i18n();
        });
   }
}

I dunno backbone.js. Working solution in normal JavaScript is here

Painful answered 7/12, 2016 at 10:45 Comment(1)
unfortunately this solution is not working for me. I think, I need to just pass the value of "lng" when it gets changed. But I don't know how can I do this? And also update the init options when "lng" get changed.Travis

© 2022 - 2024 — McMap. All rights reserved.