Skip to content

实现ejs的render函数 #24

@AILINGANGEL

Description

@AILINGANGEL
var str = `
aaaaa
<%=a%>
hhhhh
<% for(var i=0;i<list.length;i++){ %>
  <%=JSON.stringify(list[i])%>
<% }%>
bbbbb
`
var obj = {
  a: 'aaaaaaaaaa',
  list: [
    { item: '1' },
    { item: '2' },
    { item: '3' },
    { item: '4' },
    { item: '5' }
  ]
}
var s = tmpl(str, obj)
console.log(s)


// aaaaa aaaaaaaaaa    {"item":"1"}    {"item":"2"}    {"item":"3"}    {"item":"4"}    {"item":"5"}  bbbbb


function tmpl(str, obj) {
  let func = "let ans; \nwith(data){\n"
  func += "ans = `";
  str = str.replace(/<%=(.*)%>/g, (match, p) => {
    return "${" + p + "}";
  })

  str = str.replace(/<%(.*)%>/g, (match, p) => {
    return "`\n" + p + "\nans+=`"
  })

  func += str + "`\n}\nreturn ans;"
  let fn = new Function("data", func);
  return fn(obj);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions