-6

How can I create simple view engine using JavaScript 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>
brso05
  • 13,142
  • 2
  • 21
  • 40
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203

1 Answers1

0

I found the below to be proper way:

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

Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203