思路
1、用正则匹配模板中须要替换的变量并拼接成可执行的javascript语句
2、利用new Function返回render函数
3、将render函数与数据结合造成咱们须要的html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/template" id="tpl">
<% for(var i = 0; i < data.length; i++) {%>
<% if(data[i].display){ %>
<h4>
Name: <%-data[i].username%> <br> Age: <%=data[i].age%> <br> <%="tpl"%>
</h4>
<% }%>
<% }%>
</script>
<script type="text/javascript">
var tpl = document.querySelector("#tpl").innerHTML;
var templateEngine = {
//编译函数,将模板字符串编译成可执行的语句
//<%=%>须要转义,<%-%>不须要转义,<%%>为逻辑控制语句
compile: function(str) {
var tpl = str.replace(/\n/g, "\\n").replace(/<%=(.+?)%>/g, function(match, code) {
//转义输出
return "' + templateEngine.escape(" + code + ")+'";
}).replace(/<%-(.+?)%>/g, function(match, code) {
//正常输出
return "' + " + code + "+ '";
}).replace(/<%(.+?)%>/g, function(match, code) {
//逻辑控制语句
return "';\n" + code + "\ntpl += '";
});
tpl = "tpl = '" + tpl + "';";
tpl = "var tpl = '';\nwith(obj){\n" + tpl + "\n};\nreturn tpl;"
return new Function("obj", tpl);
},
//渲染函数,模板与数据相结合
render: function(compiled, data) {
return compiled(data);
},
//转义函数,将能造成html标签的字符串转换成安全字符串
escape: function(html) {
return String(html)
.replace(/&(?!\w+;)/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "]")
}
};
var compiled = templateEngine.compile(tpl);
var template = compiled({
data: [
{
username: "<h4>KAKA</h4>",
age: 33,
display: true
},
{
username: "<h4>Wade</h4>",
age: 36,
display: true
}
]
});
document.body.innerHTML = template;
</script>
</body>
</html>