Randy Gurment
Randy Gurment

Reputation: 177

How do templating engines in JavaScript work?

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>

Upvotes: 6

Views: 2702

Answers (3)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827862

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:

Upvotes: 9

Vivin Paliath
Vivin Paliath

Reputation: 95578

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>

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245479

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.

Upvotes: 2

Related Questions