How can I create simple view engine like Mustache {{ }} using JavaScript only [closed]

自闭症网瘾萝莉.ら 提交于 2019-12-20 07:56:16

问题


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:


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



来源:https://stackoverflow.com/questions/34006047/how-can-i-create-simple-view-engine-like-mustache-using-javascript-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!