Skip to content

Instantly share code, notes, and snippets.

@rahmathm1
Created June 20, 2017 09:58
Show Gist options
  • Save rahmathm1/d37e3c6ca81923b3a6fb1f25c228d69a to your computer and use it in GitHub Desktop.
Save rahmathm1/d37e3c6ca81923b3a6fb1f25c228d69a to your computer and use it in GitHub Desktop.
Simple JavaScript template function
var template = function(html, options) {
var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/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.substr(cursor, html.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment