Skip to content

Instantly share code, notes, and snippets.

@keenwon
Created December 3, 2014 08:00
Show Gist options
  • Save keenwon/d9cefdd9576ddc28c031 to your computer and use it in GitHub Desktop.
Save keenwon/d9cefdd9576ddc28c031 to your computer and use it in GitHub Desktop.
简单的javascript模板引擎
function templateEngine(tpl, data) {
var reg = /\{\{(?!\}\})(.*?)\}\}/g,
regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];\n',
cursor = 0,
match;
var add = function(line, js) {
js ? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') :
(code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
return add;
};
while (match = reg.exec(tpl)) {
add(tpl.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment