ASP 早期「代碼與 HTML 混寫」導致維護困難。本文實現一個純 JScript 編寫的模板引擎 Template,支援變量替換、區塊分割、巢狀迴圈、多模板組合,零組件、零配置、即插即用。
<%@ Language=JScript %>
<%
/*********************************************************/
/* Template Class - 輕量級 ASP 模板引擎 */
/* Author: SAYYES (www.knowsky.com) */
/* Date: 2003-06-09 */
/*********************************************************/
// 構造函數
function Template(tplPath) {
this.TplPath = tplPath;
this.TplVars = new Object(); // 模板變量存儲
}
// 載入模板文件
function Template_Load(name, filename) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(this.TplPath + "\\" + filename, 1); // 1=ForReading
this.TplVars[name] = file.ReadAll();
file.Close();
}
// 分割子模板: ...
function Template_Split(name) {
var content = this.TplVars[name];
if (!content) return;
var regex = /([\s\S]*?)/gi;
var match;
while ((match = regex.exec(content)) !== null) {
var subName = match[1];
var subContent = match[2];
this.TplVars[subName] = subContent;
// 父模板中替換為佔位符
content = content.replace(match[0], "{" + subName + "}");
}
this.TplVars[name] = content;
// 遞歸分割子模板
for (var key in this.TplVars) {
if (key != name && key != "TplPath" && key != "Load" && key != "Split" && key != "Parse") {
this.Split(key);
}
}
}
// 解析替換:{VAR} → 變量值
function Template_Parse(name) {
var content = this.TplVars[name];
if (!content) return "";
var regex = /\{(\w+)\}/g;
return content.replace(regex, function(match, key) {
return (key in this.TplVars) ? this.TplVars[key] : match;
}.bind(this));
}
// 掛載方法
Template.prototype.Load = Template_Load;
Template.prototype.Split = Template_Split;
Template.prototype.Parse = Template_Parse;
%>
<html>
<body>
<h1>{TITLE}</h1>
<!--TPLDEF:ROW-->
<tr>
<td>{ID}</td>
<td>{NAME}</td>
<td>{PRICE}</td>
</tr>
<!--TPLEND-->
<table>
<thead><tr><th>ID</th><th>名稱</th><th>價格</th></tr></thead>
<tbody>
{ROWS}
</tbody>
</table>
<p>共 {COUNT} 筆記錄</p>
</body></html>
<%@ Language=JScript %>
<!--#include file="Template.JScript.INC"-->
<%
var tpl = new Template(Server.MapPath("templates"));
tpl.Load("Main", "test.htm");
tpl.Split("Main"); // 分割出 ROW 子模板
' 模擬數據
var data = [
{id:1, name:"產品A", price:100},
{id:2, name:"產品B", price:200},
{id:3, name:"產品C", price:300}
];
var rowsHtml = "";
for (var i = 0; i < data.length; i++) {
tpl.TplVars["ID"] = data[i].id;
tpl.TplVars["NAME"] = data[i].name;
tpl.TplVars["PRICE"] = data[i].price;
rowsHtml += tpl.Parse("ROW");
}
tpl.TplVars["ROWS"] = rowsHtml;
tpl.TplVars["COUNT"] = data.length;
tpl.TplVars["TITLE"] = "產品列表";
Response.Write(tpl.Parse("Main"));
%>
Split 遞歸處理多層 Parse 僅替換當前層,手動控制順序實現巢狀渲染tpl.TplVars["NEW_VAR"] = "值" 隨時注入Load("Header","h.htm") + Load("Footer","f.htm")| 限制 | 現代替代 |
|---|---|
| 無模板繼承/佈局機制 | Razor Layout / Vue Slots / React Composition |
| 無編譯時類型檢查 | TypeScript + 模板類型定義 |
| 字符串替換性能瓶頸 | 預編譯模板 (Handlebars, EJS, Razor) |
| XSS 風險 (無自動編碼) | 內建上下文感知編碼 |
| 調試困難 | Source Map + IDE 支援 |
這個 2003 年的模板引擎展示了「字符串插值 + 區塊提取」的核心思想,至今仍是現代模板引擎的祖師爺級實現。