功能完整的模板引擎通常要解析語法,效能成本不低。另一條路是把它拆小:把一個大模板依呈現需求切成分立的模板控件,各自負責表頭、列、表尾,再由一個輕量的「填充器」組合輸出。好處是複雜度下降、效能提升,而且這些控件可以依需求自由搭配成一套可定制的模板庫。
用 <script type="text/template"> 存放模板字串,瀏覽器不會執行也不會顯示它,內容可用 .text 或 .textContent 取出:
<div id="crossRate">
<script type="text/template" id="crossRateHeader">
<table width="815" class="table-data">
<tr>
<th>代碼</th><th>名稱</th><th>最新價</th>
<th>漲跌額</th><th>漲跌幅</th><th>開盤</th>
<th>最高</th><th>最低</th><th>昨收</th>
</tr>
</table>
</script>
<script type="text/template" id="crossRateItem">
<tr>
<td>{$dataRow[1]}</td>
<td>{$dataRow[2]}</td>
<td>{$dataRow[5]}</td>
<td>{$dataRow[17]}</td>
<td>{$dataRow[18]}</td>
<td>{$dataRow[4]}</td>
<td>{$dataRow[6]}</td>
<td>{$dataRow[7]}</td>
<td>{$dataRow[3]}</td>
</tr>
</script>
<script type="text/template" id="crossRateFooter">
</table>
</script>
</div>
占位符 {$dataRow[n]} 對應後端回傳的逗號分隔字串,用索引取值最省解析成本。
function Repater(headerhtml, rowhtml, footerhtml) {
var _this = this;
var n = 0;
_this.cache = [];
_this.dic = {};
_this.header = headerhtml || '';
_this.row = rowhtml || '';
_this.footer = footerhtml || '</table>';
// 設定要替換的變數
_this.set = function (tag, val) {
this.dic[tag] = val;
};
// 解析一列,結果放進 cache
_this.parse = function (dic) {
var row = this.row,
dic = dic || this.dic,
re = /{\s*\$(\w+)(?:\[(\d+)\])?(?:\|(\w+))?\s*}/g;
var html = row.replace(re, function (a, b, c, d) {
if (typeof dic[b] == "undefined") return b;
var val = (dic[b].constructor == Array) ? dic[b][c] : dic[b];
// 支援簡易修飾符:{$name|upper}
if (Repater[d] || window[d]) {
val = (Repater[d] || window[d])(val);
}
return val;
});
_this.cache[n++] = html;
return html;
};
// 彙整成最終 HTML
_this.toHTML = function (args) {
var cache = _this.cache, result;
_this.cache = [];
n = 0;
result = _this.header + cache.join("") + _this.footer;
for (var i in args) {
if (args.hasOwnProperty(i)) {
result = result.replace("{$" + i + "}", args[i]);
}
}
return result;
};
}
(function (ns) {
function init() {
var container = document.getElementById("crossRate");
container.setAttribute("data-headertemplate",
document.getElementById("crossRateHeader").textContent);
container.setAttribute("data-itemtemplate",
document.getElementById("crossRateItem").textContent);
container.setAttribute("data-footertemplate",
document.getElementById("crossRateFooter").textContent);
}
function render(dt) {
var container = document.getElementById("crossRate"),
headerhtml = container.getAttribute("data-headertemplate"),
rowhtml = container.getAttribute("data-itemtemplate"),
footerhtml = container.getAttribute("data-footertemplate");
var repater = new Repater(headerhtml, rowhtml, footerhtml);
for (var i = 0, n = dt.length; i < n; i++) {
repater.set("dataRow", dt[i].split(","));
repater.parse();
}
container.innerHTML = repater.toHTML();
}
ns.crossRate = {
init: init,
render: render,
fill: function (data) { render(data); }
};
ns.crossRate.init();
}(window));
var datas = [
"USDEUR0,USDEUR,美元歐元,0.7731,0.7732,0.7723,...",
"USDHKD0,USDHKD,美元港幣,7.7625,7.7633,7.7621,...",
"USDJPY0,USDJPY,美元日元,79.71,79.73,79.62,..."
];
crossRate.fill(datas);
實際接後端時,把 datas 換成 Ajax 的回應即可,其餘結構不動。
值得學:把「版面骨架」與「資料綁定」分開,表頭、列、表尾各自獨立,換版型只改模板不動邏輯——這正是所有現代元件庫的核心思想。
該避免:用字串拼接加 innerHTML 輸出使用者或後端資料,等於開了 XSS 的大門。任何未經 escape() 的內容插入前都必須轉義。另外用 setAttribute 存整份模板字串也是不必要的繞路,直接從 DOM 讀 textContent 就好。今天的專案請直接採用 <template> 標籤搭配 Element.append(),或交給 Vue、React 這類框架處理。