Best practice javascript and multilanguage

后端 未结 9 1898
走了就别回头了
走了就别回头了 2020-11-29 17:37

what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 17:59

    After reading the great answers by nickf and Leo, I created the following CommonJS style language.js to manage all my strings (and optionally, Mustache to format them):

    var Mustache = require('mustache');
    
    var LANGUAGE = {
        general: {
            welcome: "Welcome {{name}}!"
        }
    };
    
    function _get_string(key) {
        var parts = key.split('.');
        var result = LANGUAGE, i;
        for (i = 0; i < parts.length; ++i) {
            result = result[parts[i]];
        }
        return result;
    }
    
    module.exports = function(key, params) {
        var str = _get_string(key);
        if (!params || _.isEmpty(params)) {
            return str;
        }
        return Mustache.render(str, params);
    };
    

    And this is how I get a string:

    var L = require('language');
    var the_string = L('general.welcome', {name='Joe'});
    

提交回复
热议问题