Could you please explain me, how do templating engines in JavaScript work? Thank you.
JSON
{ "color" : "red"}
Template
开发者_如何学JAVA<strong><%=color%></strong>
Result
<strong>Red</strong>
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
They may vary by implementation, but the one you're talking about looks like it works by doing the following:
Parse the page looking for keys in
<%= %>
tagsMatch the key to the key/value pair in the JSON
Replace the tags/key with the value.
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>
精彩评论