tags:

views:

63

answers:

3

Hello,

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>
+1  A: 

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
+3  A: 

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"}); // <strong>Red</strong>

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

Give a look to these articles:

CMS
+1  A: 

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