-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
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
Labels
No labels