Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do templating engines in JavaScript work?

Tags:

javascript

Could you please explain me, how do templating engines in JavaScript work? Thank you.

JSON

{ "color" : "red"}

Template

<strong><%=color%></strong>

Result

<strong>Red</strong>
like image 538
Randy Gurment Avatar asked Apr 19 '10 18:04

Randy Gurment


1 Answers

As a starting point I would recommend you to give a look to the String.prototype.replace method and specially using its callback function:

function replaceTokens(str, replacement) {
  return str.replace(/<\%=([^%>]+)\%>/g, function (str, match) {
    return replacement[match];
  });
}

var input = "<strong><%=color%></strong>";
replaceTokens(input, { "color" : "Red"}); 
// returns <strong>Red</strong>

replaceTokens("<%=var1%> <%=var2%>", { "var1" : "Hello", "var2": "world!"});
// returns "Hello world!"

Give a look to these articles:

  • Search and Don't Replace
  • John Resig's Micro-Templating Engine
  • Better JavaScript Templates (JSP-like syntax)
  • jQuery Templates Proposal
like image 186
Christian C. Salvadó Avatar answered Oct 25 '22 20:10

Christian C. Salvadó