-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate-engine.js
30 lines (26 loc) · 1.06 KB
/
template-engine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line
(function(window) {
"use strict";
const 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);
};
if (typeof define === "function" && define.amd) {
// AMD
define(template);
} else {
// browser global
window.template = template;
}
})(window);