模闆渲染:根據模闆來渲染資料!!!在ES6 中模闆字元串用反引号表示。
let str =
我是字元串
;
下面進入正題:
我們先自己建立一個模闆:
<script type="text/html" id="template">
<ul>
<% for(var i = 0 ; i < 10 ; i ++){ %>
<li>
<strong> <%= i %></strong>
</li>
<% } %>
</ul>
</script>
注意點:
1、因為模闆裡肯定包含js,是以我們對js特殊标記:<%這裡邊寫js%>
2、HTML在我們眼中就是字元串,是以不用包裹
3、輸出的變量,我們用<%=%>包裹
接下來:
先處理HTML标簽:
自定義一個print方法用來拼接标簽。
再處理js代碼的包裹以及特殊的輸出的變量的包裹:
這裡我們使用正則處理:
HTML标簽處理的正則:
/<%^=%>/g
輸出變量處理的正則:
/<%=(.*?)%>/g
接下來進行拼接:
自定義一個函數用來拼接處理好的字元串
以上我們可以進行一波封裝:
function renderTemplate( template_str , data ){
template_str = template_str.replace(/<%[^=](.*?)%>/g ,`\`); \n $1 \n print(\`` );
template_str = template_str.replace(/<%=(.*?)%>/g ,`\`); \n print($1) \n print(\`` );
template_str = `print(\`${ template_str }\`)`;
var fn_str = `(function( data ){
var html = "";
function print(str){
html += str
}
${template_str} // 這是剛才解析好的模闆;
return html;
})`;
var temp_fn = eval( fn_str );
var res = temp_fn( data );
return res;
}
這樣我們就封裝好了。
最終我們就可以直接在頁面渲染了!!!