How to use Knockout observables in i18next?

后端 未结 4 443
抹茶落季
抹茶落季 2021-01-20 00:10

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

4条回答
  •  无人共我
    2021-01-20 00:28

    Thanks for a great example, @robert.westerlund!

    I slightly modified your example to better fit my needs:

    ko.bindingHandlers['i18n'] = {
            update: function (element, valueAccessor, allBindings) {
                var key = ko.unwrap(valueAccessor()),
                    options = ko.toJS(allBindings.get('i18n-options') || {}),
                    translation = i18next.t(key, options);
    
                // Check whether the translation contains markup
                if (translation.match(/<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/)) {
                    element.innerHTML = translation;
                } else {
                    // Check whether the translation contains HTML entities
                    if (translation.match(/&(?:[a-z]+|#x?\d+);/gi)) {
                        element.innerHTML = translation;
                    } else {
                        // Treat translation as plain text
                        element.innerText = translation;
                    }
                }
            }
        };
    

提交回复
热议问题