-4

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>
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • If this technique was actually that simple, Mustache wouldn't need to exist. I'd use Mustache or something like it so you don't have to deal with the issues they already have. – Blazemonger Nov 30 '15 at 19:44
  • @Blazemonger it is not to have the solution, I want to understand the solution, not just use it. – Hasan A Yousef Nov 30 '15 at 19:45
  • 1
    I must say this question has been unfairly 'put on hold' as there are literally thousands upon thousands of questions on SO which ask for specific *broad* things such as this question. – AmmarCSE Nov 30 '15 at 19:54

1 Answers1

0

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

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