Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let template = "\<div id='div'\>This is <%this.msg.one%>, say <%this.words%>\<\/div\>";
- template+= "<%for(var i = 0; i<this.last.length; i++){%>"
- template+= "<%this.last[i]%> !"
- template+= "<%}%>"
- function render(tpl, data){
- let pattern = /<%([^%>]+)?%>/g,
- keyRegx = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
- code = "var r = [];\n", cursor = 0
- /* var r = [];
- * r.push(prevString);
- * r.push(matchWord);
- * r.push(lastString);
- * return r.join("");
- */
- let add = (line, isJs) => {
- code += isJs ?
- line.match(keyRegx) ? line+"\n" : 'r.push('+line+');\n'
- : 'r.push("'+line.replace(/"/g, '\\"')+'");\n';
- }
- while(match = pattern.exec(tpl)){
- add(tpl.slice(cursor, match.index))
- add(match[1], true)
- cursor = match.index + match[0].length
- // tpl = tpl.replace(match[0], data[match[1]])
- }
- add(tpl.substr(cursor, tpl.length - cursor))
- code += 'return r.join("");'
- console.log(code)
- return (new Function(code.replace(/[\r\n\t]/g, ''))).call(data)
- }
- document.body.innerHTML = render(template, {
- msg: { one: "div"},
- words: "hi",
- last: ["bye", "bye"]
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement