如何创建像Mustache这样的简单视图引擎,以便将{{}}之间的单词替换为其值,如:
<p>hey there {{ codeName }}</p>
codeName = 'JavaScript 6'
so that it be converted to:
<p>hey there JavaScript 6</p>
答案 0 :(得分:0)
我发现以下是理解它的正确方法:
var templater = function(html){
return function(data){
for(var x in data){
var re = "{{\\s?" + x + "\\s?}}";
html = html.replace(new RegExp(re, "ig"), data[x]);
}
return html;
};
};
var template = new templater("<p>hey there {{ codeName }}</p>");
var div = document.createElement("div");
div.innerHTML = template({
codeName: "JavaScript 6"
});
document.body.appendChild(div);
参考是here