ejs模板引擎原理

1,389 阅读1分钟
核心
  • 把html中的<%%>中的<%%>中的js保留执行,<%=%>替换成${xxx}拼接到模板字符串上,test一执行返回的字符串就是我们要的html
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);

-形象点但是难看点:

 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