var template = function(tpl, data) { var re = /{{(.+?)}}/g, cursor = 0, reExp = /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g, code = 'var r=[];\n'; function parsehtml(line) { line = line.replace(/('|")/g, '\\$1').replace(/\n/g, ' ').replace(/(^\s+)|(\s+$)/g,""); code +='r.push("' + line + '");\n'; } function parsejs(line) { line = line.replace(/(^\s+)|(\s+$)/g,""); code += line.match(reExp)? line + '\n' : 'r.push(' + 'this.' + line + ');\n'; } while((match = re.exec(tpl))!== null) { parsehtml(tpl.slice(cursor, match.index)); parsejs(match[1]); cursor = match.index + match[0].length; } parsehtml(tpl.substr(cursor, tpl.length - cursor)); code += 'return r.join("");'; return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); }