思路
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>