How to make client side I18n with mustache.js

后端 未结 5 1633
北荒
北荒 2021-02-08 21:11

i have some static html files and want to change the static text inside with client side modification through mustache.js.

it seems that this was possible Twitter\'s mu

5条回答
  •  借酒劲吻你
    2021-02-08 21:25

    This is quite simple and pretty straightforward.

    First, you will need to add code to determine the Query String lang. For this, I use snippet taken from answer here.

    function getParameterByName(name) {
    
        var match = RegExp('[?&]' + name + '=([^&]*)')
                        .exec(window.location.search);
    
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    
    }
    

    And then, I use jQuery to handle ajax and onReady state processing:

    $(document).ready(function(){
        var possibleLang = ['en', 'id'];
        var currentLang = getParameterByName("lang");
        console.log("parameter lang: " + currentLang);
        console.log("possible lang: " + (jQuery.inArray(currentLang, possibleLang)));
        if(jQuery.inArray(currentLang, possibleLang) > -1){
            console.log("fetching AJAX");
            var request = jQuery.ajax({
                processData: false,
                cache: false,
                url: "data_" + currentLang + ".json"
            });
            console.log("done AJAX");
    
            request.done(function(data){
                console.log("got data: " + data);
                var output = Mustache.render("

    {{title}}

    {{content}}
    ", data); console.log("output: " + output); $("#output").append(output); }); request.fail(function(xhr, textStatus){ console.log("error: " + textStatus); }); } });

    For this answer, I try to use simple JSON data:

    {"title": "this is title", "content": "this is english content"}
    

    Get this GIST for complete HTML answer.

提交回复
热议问题