DIV CSS 佈局教程網

用 jQuery 外掛實作輕量模板引擎,把 JSON 渲染成表格
編輯:JQuery特效代碼     

前端拿到 JSON 之後要渲染成 HTML,如果資料量不大、又不想引入額外的模板庫,其實幾十行就足夠了。這裡的實作靈感來自 jQuery 官方的 tmpl 早期原型。

一、模板引擎本體

$.fn.parseTemplate = function (data) {
    var str = (this).html();
    var _tmplCache = {};
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                "with(obj){p.push('" +
                str.replace(/[\r\t\n]/g, " ")
                   .replace(/'(?=[^#]*#>)/g, "\t")
                   .split("'").join("\\'")
                   .split("\t").join("'")
                   .replace(/<#=(.+?)#>/g, "',$1,'")
                   .split("<#").join("');")
                   .split("#>").join("p.push('") +
                "');}return p.join('');";

            func = new Function("obj", strFunc);
            _tmplCache[str] = func;      // 同一份模板只編譯一次
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
};

它做的事就是把模板字串翻譯成一段 JavaScript 函式主體,用 new Function 動態編譯,並用模板字串本身當快取 key,同一份模板只編譯一次,後續呼叫只是拼陣列再 join。

語法只有兩個標記:<# ... #> 是程式碼區塊,<#= ... #> 是輸出運算式。

二、撰寫模板

用一個 type="text/html" 的 script 標籤包住模板,這樣瀏覽器不會渲染它、也不會當成 JS 執行:

<script id="template" type="text/html">
<table style="width:400px;">
<thead>
<tr><th>name</th><th>age</th><th>date</th><th>type</th></tr>
</thead>
<tbody>
<#
var xing = items.pm;
#>
<tr>
  <td><#= xing.key #></td>
  <td><#= xing.key1 #></td>
  <td><#= xing.key #></td>
  <td><#= items.pm1 #></td>
</tr>
<#
#>
</tbody>
</table>
<br />
<#= items.pm.length #> 記錄
</script>

三、呼叫

$(function () {
    var json = { "items": { "pm": { "key": "value", "key1": "value1" }, "pm1": "pmvalue" } };
    var output = $('#template').parseTemplate(json);
    $('#cc').html(output);
});

就這樣。想支援清單遍歷時,在 <# #> 區塊裡寫 JavaScript 迴圈即可,例如 <# for (var i = 0; i < items.length; i++) { #> ... <# } #>。

四、使用上的注意事項

這個實作有兩個明顯限制,正式環境使用前要留意:

  • 用了 with(obj) 與 new Function,在 strict mode 底下 with 是禁用語法,部分 CIS 政策也會攔 eval 系列呼叫。
  • 沒有做 HTML 轉義。如果 JSON 裡含有使用者輸入,直接輸出等於埋下 XSS 風險,模板中該用一個 escape() 輔助函式包一層。

如果專案對這兩點有要求,建議改用 jQuery Templates、Handlebars 或 doT 這類成熟方案;反之若只是內部工具、資料來源可控,這個 20 行的版本反而最輕巧。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved