如何使用 i18next 插件切换语言?

How to switch languages with the i18next plugin?

我在我的应用程序中使用 Backbone.js 并在我的应用程序中使用 i18next 插件作为我的语言切换功能。当我将值传递给 init 函数调用中的 lng 选项时,它会正确翻译我的页面。

现在我想通过语言选择器动态地执行此操作。我有四种语言的 <select>,我想将所选语言的值传递给 init 函数的 lng 选项。

这是我的代码:

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();
    });
}
$(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();
        });
   }
}

我不知道 backbone.js。 Working solution in normal JavaScript is here

更改语言的函数是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(函数)。

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();
});

在带有语言选择器的视图中:

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

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

概念验证

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>

关于翻译语言名称,请查看Language of language names in the language selector?