I\'m trying to somehow dynamically use i18next translations together with Knockout.js, but I cant figure out how.
Neither a custom Knockout binding or the i18next jQ
I'm not very familiar with i18next, so I might be using i18next incorrectly, but you could easily achieve this by creating a bindingHandler. A very simple version of such a bindingHandler, which supports passing optional options, could look like:
ko.bindingHandlers['translatedText'] = {
update: function(element, valueAccessor, allBindings){
var key = ko.unwrap(valueAccessor());
var options = ko.toJS(allBindings.get('translationOptions') || {});
var translation = i18n.t(key, options);
element.innerText = translation;
}
};
Given the following i18next initialization code:
i18n.init({
lng: "en",
debug: true,
resStore: {
en: {
translation: {
'myTextKey': 'My translated value is "__value__"',
'otherTextKey': 'This is just a text which does not use options'
}
}
}
});
You could use it with the following HTML:
And the following view model:
function ViewModel(){
this.input = ko.observable();
}
ko.applyBindings(new ViewModel);
I have saved the above code to a jsfiddle which you can find at http://jsfiddle.net/md2Hr/