template.js 1.0 KB

1234567891011121314151617181920212223
  1. // N2O Simple Template
  2. function template(html, data) { // template("{this.name}",{name:"Maxim"})
  3. var re = /{([^}]+)?}/g, code = 'var r=[];', cursor = 0;
  4. var add = function(line,js) {
  5. js? (code += 'r.push(' + line + ');') :
  6. (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");' : ''); // "
  7. return add; }
  8. while(match = re.exec(html)) {
  9. add(html.slice(cursor, match.index))(match[1],true);
  10. cursor = match.index + match[0].length; }
  11. add(html.substr(cursor, html.length - cursor));
  12. code += 'return r.join("");';
  13. return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); }
  14. function xml(html) { return new DOMParser().parseFromString(html, "application/xhtml+xml").firstChild; }
  15. function dom(html) {
  16. try { return new DOMParser().parseFromString(html, "text/html").firstChild.getElementsByTagName("body")[0].firstChild; }
  17. catch (ex) { var temp = document.createElement("DIV");
  18. temp.innerHTML = html;
  19. return temp.firstChild; }
  20. }