-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate-compile.mjs
50 lines (45 loc) · 1.16 KB
/
template-compile.mjs
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function compile(template) {
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template
.replace(evalExpr, '`); \n echo( $1 );\n echo(`')
.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`)';
const script = `
(function parse(data){
var output = "";
function echo(html){
output += html;
}
${template}
return output;
})`;
return script;
}
let template = `
<ul>
<% for(var i=0;i<data.supplies.length;i++) { %>
<li><%= data.supplies[i] %></li>
<% } %>
</ul>
`;
const parse = eval(compile(template));
console.log(parse({ supplies: ["broom", "mop", "cleaner"] }));
/**
(function parse(data) {
var output = "";
function echo(html) {
output += html;
}
将非代码部分作为作为echo函数参数。代码逻辑部分作为正常js代码,%=输出部分代码也作为echo的参数拼接输出
最后将模板的分割融入到js可操作逻辑内。parse函数被正常解析就成了
echo(`<ul>`);
for (var i = 0; i < data.supplies.length; i++) {
echo(`<li>`);
echo(data.supplies[i]);
echo(`</li>`);
}
echo(`</ul>`)
return output;
})
*/