Skip to content

Commit 30952a6

Browse files
authored
implementation: use split for template parsing (#10)
1 parent 138e9f6 commit 30952a6

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

lib/micro-template.js

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,23 @@ const template = function (id, data) {
88
let name = id, string = /^[\w\-]+$/.test(id) ? me.get(id): (name = 'template(string)', id); // no warnings
99
let line = 1;
1010
const body = (
11-
"try { " +
12-
(me.variable ? "let " + me.variable + " = __this.stash;" : "with (__this.stash) { ") +
13-
"__this.ret += '" +
14-
string.
15-
replace(/<%/g, '\x11').replace(/%>/g, '\x13'). // if you want other tag, just edit this line
16-
replace(/\\(?![^\x11\x13]+?\x13)/g, '\\x5c'). // escape backslash of outside of tag
17-
replace(/'(?![^\x11\x13]+?\x13)/g, '\\x27'). // escape single quote of outside of tag
18-
replace(/^\s*|\s*$/g, '').
19-
replace(/\n|\r\n/g, function () { return "';\n__this.line = " + (++line) + "; __this.ret += '\\n" }).
20-
replace(/\x11=raw(.+?)\x13/g, "' + ($1) + '").
21-
replace(/\x11=(.+?)\x13/g, "' + __this.escapeHTML($1) + '").
22-
replace(/\x11(.+?)\x13/g, "'; $1; __this.ret += '") +
23-
"'; " + (me.variable ? "" : "}") + "return __this.ret;" +
24-
"} catch (e) { throw new Error('TemplateError: ' + e + ' (on " + name + "' + ' line ' + __this.line + ')'); } " +
25-
"//@ sourceURL=" + name + "\n" // source map
26-
).replace(/__this\.ret \+= '';/g, '').replace(/\x11/g, '<%').replace(/\x13/g, '%>');
11+
`try { ` +
12+
(me.variable ? `let ${me.variable} = __this.stash;` : `with (__this.stash) { /*start*/`) +
13+
string.trim().split(/(<%.+?%>)/g).map(part =>
14+
part.startsWith('<%=raw') && part.endsWith('%>') ? `/*raw*/__this.ret+=(${part.slice(6, -2)});` :
15+
part.startsWith('<%=') && part.endsWith('%>') ? `/*=*/__this.ret+=__this.escapeHTML(${part.slice(3, -2)});` :
16+
part.startsWith('<%') && part.endsWith('%>') ? `/* */${part.slice(2, -2)};` :
17+
(
18+
part = part.replace(/\\/g, "\\\\")
19+
.replace(/'/g, "\\'")
20+
.replace(/\n|\r\n/g, () => `\\n';\n__this.line = ${++line}; __this.ret += '`),
21+
part ? `/*+*/__this.ret+='${part}';` : ''
22+
)
23+
).join('') +
24+
`/*end*/ ${me.variable ? "" : "}"} return __this.ret;` +
25+
`} catch (e) { throw new Error('TemplateError: ' + e + ' (on ${name} line ' + __this.line + ')'); }` +
26+
`//@ sourceURL=template.js\n`
27+
);
2728
const func = new Function("__this", body);
2829
const map = { '&' : '&amp;', '<' : '&lt;', '>' : '&gt;', '\x22' : '&#x22;', '\x27' : '&#x27;' };
2930
const escapeHTML = function (string) { return (''+string).replace(/[&<>\'\"]/g, function (_) { return map[_] }) };

0 commit comments

Comments
 (0)