Search code examples
breezesingle-page-applicationdurandalhottowel

How to implement multilingualism in SPA


I'm currently struggling with the problem of multilingualism in an SPA.

I've come up with several solutions, like building a wrapper for the resources resx files, or saving all labels in the database, but I am wondering if any of you have found some solution which automates these steps.

Are there any practices which are specific for this problem?


Solution

  • I've solved my own problem, using a custom binding and i18next.

    First, I've implemented i18next for translation of my labels/buttons and other resources.

    Secondly, I've added a custom Knockout bindingHandler:

    ko.bindingHandlers.i18n = {
        init: function (element, valueAccessor) {        
            var translateKey = valueAccessor();
            ko.utils.setTextContent(element, $.t(translateKey));
        }
    };
    

    Finally you can add the following code to your views:

    <span data-bind="i18n : 'buttons.cancel'"></span>
    

    This will automatically get the correct resource, and Knockout will handle the bindings.

    Hopefully this will help others struggling with the same problem.