Skip to content

Instantly share code, notes, and snippets.

@yesvods
Created April 4, 2016 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yesvods/98dd678cdba6c1719b9ecfac704ae9d7 to your computer and use it in GitHub Desktop.
Save yesvods/98dd678cdba6c1719b9ecfac704ae9d7 to your computer and use it in GitHub Desktop.
Javascript template engine
function template(html, data){
//process html template
html = html.replace(/>/g, ">")
.replace(/&lt;/g, "<")
.replace(/[\r\t\n]\s+/g, '')
.trim();
var re = /<%([^>]+)?%>/g,
reExp = /(^( )?(if|for|else|switch|case|break|{|}|var|let|const))(.*)?/g,
code = 'var r=[];\n',
cursor = 0,
match;
var add = function(line, js) {
js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + 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.slice(cursor));
code += 'return r.join("");';
return new Function(code).apply(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment