Skip to content

Instantly share code, notes, and snippets.

@youmad
Created January 11, 2016 19:34
Show Gist options
  • Save youmad/2bd3d8195f2a28a59c21 to your computer and use it in GitHub Desktop.
Save youmad/2bd3d8195f2a28a59c21 to your computer and use it in GitHub Desktop.
Micro template engine in JS.
var tplNgn = function(qs, opts) {
var html = document.querySelector(qs).innerHTML;
var re = /<%([^%>]+)?%>/g;
var reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g;
var code = 'var r=[];\n';
var cursor = 0;
var match;
var add = function(line, js) {
if (js) {
code += (line.match(reExp))
? line + '\n'
: 'r.push(' + line + ');\n';
} else {
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(opts);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment