能否请您解释一下,JavaScript中的模板引擎如何工作?谢谢.
JSON
{ "color" : "red"}
Run Code Online (Sandbox Code Playgroud)
模板
<strong><%=color%></strong>
Run Code Online (Sandbox Code Playgroud)
结果
<strong>Red</strong>
Run Code Online (Sandbox Code Playgroud)
作为一个起点,我建议你看一下String.prototype.replace方法,特别是使用它的回调函数:
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!"
Run Code Online (Sandbox Code Playgroud)
看看这些文章: