js原生实现一个简单的模版引擎

  • 代码如下
    var template = "

    Name: {{name}}
    Company:{{company}}

    City:{{city}}

    ",
    me = {
    name: "sdcV",
    email: "[email protected]",
    company: "Microsoft",
    city: "London"
    };
    function applyDataToTemplate(templateString, dataObject) {
    var key, value, regex;
    for(key in dataObject){
    regex = new RegExp("{{" + key + "}}", "g");
    value = dataObject[key];

           templateString = templateString.replace(regex, value);
       }
        return templateString;
    }
    alert(applyDataToTemplate(template, me));

你可能感兴趣的:(js原生实现一个简单的模版引擎)