nodejs模板引擎
function render(str, data) {
var tpl = str.replace(/<%=([\s\S]+?)%>/g, function (match, code) {
if (match) {
return "'+obj." + code + "+'";
}
});
console.log(tpl);
tpl = "var tpl='" + tpl + "'\nreturn tpl";
console.log(tpl);
var complied = new Function('obj', tpl);
return complied(data);
}
console.log(render('hello <%=userName%>.', {userName: "li"}));
输出为:
hello '+obj.userName+'.
var tpl='hello '+obj.userName+'.'
return tpl
hello li.
tpl = "var tpl='" + tpl + "'\nreturn tpl";
function(obj){
var tpl='hello '+obj.userName+'';
return tpl;
}
用 Function 类直接创建函数的语法如下:
var function_name = new function(arg1, arg2, ..., argN, function_body)
function sayHi(sName, sMessage) {
alert("Hello " + sName + sMessage);
}
//也可以定义为
var sayHi = new Function("sName", "sMessage", "alert(\"Hello \" + sName + sMessage);");
//利用预编译缓存模板编译后的结果,实际应用中就可以实现一次编译,多次执行
var compile = function (str) {
var tpl = str.replace(/<%=([\s\S]+?)%>/g, function (match, code) {
if (match) {
return "'+obj." + code + "+'";
}
})
tpl = "var tpl='" + tpl + "'\nreturn tpl";
console.log(tpl);
return new Function('obj', tpl);
}
var render = function (compiled, data) {
return compiled(data);
}
var compiled = compile('hello <%=userName%> .');
console.log(render(compiled,{userName:'swa'}));

浙公网安备 33010602011771号