6

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>
Randy Gurment
  • 177
  • 2
  • 6
  • Your question is not very clear. Can you provide more context? – Vivin Paliath Apr 19 '10 at 18:17
  • 2
    I think that in general the approach for making a template engine is to select the appropriate algorithms and implement them using best-practice techniques to achieve the desired result. – Pointy Apr 19 '10 at 18:19

3 Answers3

9

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:

steviesh
  • 1,740
  • 6
  • 19
  • 33
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
2

They may vary by implementation, but the one you're talking about looks like it works by doing the following:

  1. Parse the page looking for keys in <%= %> tags

  2. Match the key to the key/value pair in the JSON

  3. Replace the tags/key with the value.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

It's not very different from other templating solutions (at the conceptual level).

{ "color" : "red"}

Specifies a color attribute with the value red.

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

Means "Use the value of color wherever I have <%=color%>. Based on wahat you have, the templating-engine probably walks the DOM and finds nodes that have values that match <%=somestring%>. Then, it checks to see if there is an attribute that matches the somestring value. If there is one, it replaces the value of <%=somestring%> with the value defined in the JSON (which, in this case is red).

This finally gives you:

<strong>Red</strong>
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295