Advertisement
Guest User

Untitled

a guest
Aug 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. let template = "\<div id='div'\>This is <%this.msg.one%>, say <%this.words%>\<\/div\>";
  2. template+= "<%for(var i = 0; i<this.last.length; i++){%>"
  3. template+= "<%this.last[i]%> !"
  4. template+= "<%}%>"
  5.  
  6. function render(tpl, data){
  7. let pattern = /<%([^%>]+)?%>/g,
  8. keyRegx = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
  9. code = "var r = [];\n", cursor = 0
  10. /* var r = [];
  11. * r.push(prevString);
  12. * r.push(matchWord);
  13. * r.push(lastString);
  14. * return r.join("");
  15. */
  16. let add = (line, isJs) => {
  17. code += isJs ?
  18. line.match(keyRegx) ? line+"\n" : 'r.push('+line+');\n'
  19. : 'r.push("'+line.replace(/"/g, '\\"')+'");\n';
  20. }
  21.  
  22. while(match = pattern.exec(tpl)){
  23. add(tpl.slice(cursor, match.index))
  24. add(match[1], true)
  25. cursor = match.index + match[0].length
  26. // tpl = tpl.replace(match[0], data[match[1]])
  27. }
  28. add(tpl.substr(cursor, tpl.length - cursor))
  29. code += 'return r.join("");'
  30. console.log(code)
  31. return (new Function(code.replace(/[\r\n\t]/g, ''))).call(data)
  32. }
  33.  
  34. document.body.innerHTML = render(template, {
  35. msg: { one: "div"},
  36. words: "hi",
  37. last: ["bye", "bye"]
  38. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement