实现一个模板引擎

<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
<div id="container"></div>
<script type="text/html" id="user_tmpl">
<%for ( var i = 0; i < users.length; i++ ) { %>
<li>
<a href="<%=users[i].url%>">
<%=users[i].name%>
</a>
</li>
<% } %>
</script>
<script>
// 模板引擎第二版
(function () {
this.tmpl = function (str, data) {
var str = document.getElementById(str).innerHTML;
var fn = new Function("obj",
"var p = []; p.push('" +
str
.replace(/[\r\t\n]/g, "")
.replace(/<%=(.*?)%>/g, "');p.push($1);p.push('")
.replace(/<%/g, "');")
.replace(/%>/g, "p.push('") +
"');return p.join('');");
return fn(data);
};
})();
var results = document.getElementById("container");
var users = [{
"name": "Byron",
"url": "http://localhost"
},
{
"name": "Casper",
"url": "http://localhost"
},
{
"name": "Frank",
"url": "http://localhost"
}
]
results.innerHTML = tmpl("user_tmpl", users);
</script>
</body>
</html>
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
51
52
53
54
55
56
57
58
59
60
61
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
51
52
53
54
55
56
57
58
59
60
61
上次更新: 2022/09/07, 15:54:26