如何仅使用 JavaScript 创建像 Mustache {{ }} 这样的简单视图引擎
How can I create simple view engine like Mustache {{ }} using JavaScript only
如何创建像 Mustache 这样的简单视图引擎,以便 {{ }} 之间的单词被其值替换,例如:
<p>hey there {{ codeName }}</p>
codeName = 'JavaScript 6'
so that it be converted to:
<p>hey there JavaScript 6</p>
我发现以下是理解它的正确方法:
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
如何创建像 Mustache 这样的简单视图引擎,以便 {{ }} 之间的单词被其值替换,例如:
<p>hey there {{ codeName }}</p>
codeName = 'JavaScript 6'
so that it be converted to:
<p>hey there JavaScript 6</p>
我发现以下是理解它的正确方法:
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