核心:通过正则匹配替换字符串,whit用法 去实现。
例如ejs中<% %> <%= %>
let fs = require('fs');
let path = require('path');
let str = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf8');
function render(str,obj){
let head = 'let str = ""\r\nwith(obj){\r\n';
head+= 'str+= `';
str = str.replace(/<%=(.+?)%>/g,function () {
return '${' + arguments[1] + '}';
})
let content = str.replace(/<%(.+?)%>/g,function () {
return '`\r\n'+arguments[1] + '\r\nstr+=`';
});
let tail = '`\r\n return str}';
let fn = new Function('obj', head + content + tail);
return fn(obj);
}
let newStr = render(str,{
arr:[1,2,3]
});
console.log(newStr)