博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ejs模板引擎原理
阅读量:7234 次
发布时间:2019-06-29

本文共 1276 字,大约阅读时间需要 4 分钟。

核心
  • 把html中的<%%>中的<%%>中的js保留执行,<%=%>替换成${xxx}拼接到模板字符串上,test一执行返回的字符串就是我们要的html
function test(obj) {  let templ = ''  with (obj) {    templ += `
Document`; arr.forEach(item => { templ += `
  • ${item.age}
  • `; }) templ += `` } 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 += `
    Document//<% arr.forEach(item => { %>(替换前后一目了然的对应注释) `; arr.forEach(item => { templ += `//
  • <%=item%>
  • (替换前后一目了然的对应注释)
  • ${item.age}
  • // <% }) %>(替换前后一目了然的对应注释) `; }) templ += ``}return templ复制代码

    转载地址:http://yxlfm.baihongyu.com/

    你可能感兴趣的文章
    iOS 静态库,动态库与 Framework 浅析
    查看>>
    Java对ArrayList进行排序
    查看>>
    NumberFormat
    查看>>
    Spring WebSocket初探1 (Spring WebSocket入门教程)<转>
    查看>>
    每天一个linux命令(01):ifconfig命令
    查看>>
    vim打造简易C语言编辑器(在用2016.7.10)
    查看>>
    Response.Cookies 和 Request.Cookies
    查看>>
    Unity之定时调用
    查看>>
    [工具] 葡萄集
    查看>>
    I/O复用机制概述
    查看>>
    给JBoss种蛊分析
    查看>>
    winform按钮和子按钮
    查看>>
    行为类模式(八):状态(State)
    查看>>
    LINUX磁盘分区、格式化、挂载、卸载全程详解
    查看>>
    Liferay7 BPM门户开发之19: 理解Service Builder体系
    查看>>
    越狱后的ios如何用apt-get 安装各种命令
    查看>>
    JDBC、JTA、Spring的事务管理
    查看>>
    浏览器记住密码、浏览器记住密码表单自动加载
    查看>>
    洛谷P1280 尼克的任务[DP]
    查看>>
    Tomcat利用Redis存储Session
    查看>>