template.htm 937 B

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