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>
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With