Advertisement
Guest User

Untitled

a guest
Aug 28th, 2015
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. var compileTemplate = function(html) {
  2. var re = /{{([^}]*(?:}[^}]+)*}*)}}/g,
  3. reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
  4. code = 'var r=[];\n', cursor = 0, match;
  5.  
  6. var add = function(line, js) {
  7. js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
  8. (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
  9. return add;
  10. }
  11. while(match = re.exec(html)) {
  12. add(html.slice(cursor, match.index))(match[1], true);
  13. cursor = match.index + match[0].length;
  14. }
  15. add(html.substr(cursor, html.length - cursor));
  16. code += 'return r.join("");';
  17.  
  18. var template = new Function(code.replace(/[\r\t\n]/g, ''));
  19. return template;
  20. }
  21.  
  22.  
  23. function generateTemplate(selector){
  24. var el = document.querySelector(selector);
  25. if(el.type.toLowerCase()=="template/html"){
  26. return compileTemplate(el.innerHTML);
  27. }
  28. else throw Error("Type of '"+selector+"' is not a template/html");
  29. }
  30.  
  31. var data = {
  32. title : "Hello",
  33. list : [1,2]
  34. }
  35.  
  36. var test = generateTemplate("#t2");
  37. document.body.innerHTML = test.apply(data);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement