How can I create simple view engine like Mustache

2019-03-07 07:15发布

How can I create simple view engine like Mustache, so that the word between the {{ }} is replaced by its value, like:

<p>hey there {{ codeName }}</p>
codeName = 'JavaScript 6'
so that it be converted to:

<p>hey there JavaScript 6</p>

1条回答
地球回转人心会变
2楼-- · 2019-03-07 07:36

I found the below to be proper way to understand it:

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);

reference is here

查看更多
登录 后发表回答