function test(obj) {
let templ = ''
with (obj) {
templ += `<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body>`;
arr.forEach(item => {
templ += `<li>${item.age}</li>`;
})
templ += `</body></html>`
}
return templ
}
复制代码
const fs = require('fs');
const path = require('path');
let str = fs.readFileSync(path.resolve(__dirname, 'index2.html'), 'utf8')
function render(str) {
let head = `let templ='' `;
head += `with (obj){ `;
let content = `templ+=\``;
//<%=%>替换成${xxx}
str = str.replace(/<%=([\s\S]*?)%>/g, function () {
return '${' + arguments[1] + '}';
})
//匹配<%%>,替换<%成反引号,替换%>成templ+=`,构成模板字符串
content += str.replace(/<%([\s\S]*?)%>/g, function () {
return `\`; ${arguments[1]} templ+=\``;
})
let tail = `\`} return templ`;
return head + content + tail;
}
let res = render(str)
console.log(res);
//用字符串建立一个函数
let fn = new Function('obj', res);
let result = fn({
name: 'lrj',
arr: [{ age: 123 }, { age: 456 }]
})
console.log(result);
复制代码
-形象点可是难看点:html
let templ = ''
with (obj) {
templ += `<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body> //<% arr.forEach(item => { %>(替换先后一目了然的对应注释) `; arr.forEach(item => { templ += ` //<li><%=item%></li>(替换先后一目了然的对应注释) <li>${item.age}</li> // <% }) %>(替换先后一目了然的对应注释) `; }) templ += ` </body></html> `}
return templ
复制代码