Created
January 26, 2014 08:29
-
-
Save MaxMorais/8630145 to your computer and use it in GitHub Desktop.
Smallest JavaScript template engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function TemplateEngine(html, options) { | |
var re = /<%(.+?)%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}|;))(.*)?/g, code = 'var r=[];\n', cursor = 0, result; | |
var add = function(line, js) { | |
js? (code += line.match(reExp) ? line + '\n' : 'r.push(this.' + line + ');\n') : | |
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : ''); | |
return add; | |
} | |
while(match = re.exec(html)) { | |
add(html.slice(cursor, match.index))(match[1], true); | |
cursor = match.index + match[0].length; | |
} | |
add(html.substr(cursor, html.length - cursor)); | |
code = (code + 'return r.join("");').replace(/[\r\t\n]/g, ''); | |
console.log(code); | |
try { result = new Function(code).apply(options); } | |
catch(err) { console.error("'" + err.message + "'", " in \n\nCode:\n", code, "\n"); } | |
return result; | |
} | |
function Template(html){ | |
return { | |
'html': html, | |
'render': function(options){ return TemplateEngine(this.html, options); }, | |
'toString': function (){ return 'Template: '+this.html; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment