把動態內容落成靜態 HTML 檔,是降低伺服器負擔的常見手法。實作上有兩條路,先說結論:範例採用第一種。
用 Dreamweaver MX 這類工具先做出漂亮的 HTML 模板,在需要動態填充的位置埋特殊標記(例如 $Htmlformat$)。生成時讀取模板、把前台送來的內容填進標記位置,另存新檔寫入磁碟,再把相關資料寫進資料庫。
直接用程式碼組出 HTML,可以借助 HtmlTextWriter 類別輸出。
硬編碼方式的工作量大得驚人,需要大量 HTML 程式碼,除錯困難。更麻煩的是樣式寫死之後無法調整——網站一旦換版,就得重新編碼,後續維護成本極高。這正是本文採用思路一的原因。
1. 定義模板 template.htm
<Html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/Html; charset=gb2312">
</head>
<body>
<table $Htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000">
<tr>
<td width="100%" valign="middle" align="left">
<span style="color: $Htmlformat[1]; font-size: $Htmlformat[2]">$Htmlformat[3]</span>
</td>
</tr>
</table>
</body>
</Html>
2. ASP.NET 端程式碼
// 讀取 Html 模板到 StringBuilder
string[] format = new string[4]; // 長度需與模板中的標記數量一致
StringBuilder Htmltext = new StringBuilder();
try
{
using (StreamReader sr = new StreamReader("存放模板頁面的路徑和頁面名"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Htmltext.Append(line);
}
sr.Close();
}
}
catch
{
Response.Write("<Script>alert('讀取文件錯誤')</Script>");
}
// 給標記陣列賦值
format[0] = "background=\"bg.jpg\""; // 背景圖片
format[1] = "#990099"; // 字體顏色
format[2] = "150px"; // 字體大小
format[3] = "<marquee>生成的模板Html頁面</marquee>"; // 文字說明
// 逐一替換模板中的標記
for (int i = 0; i < 4; i++)
{
Htmltext.Replace("$Htmlformat[" + i + "]", format[i]);
}
// 輸出 htm 檔
try
{
using (StreamWriter sw = new StreamWriter("存放路徑和頁面名", false, System.Text.Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(Htmltext);
sw.Flush();
sw.Close();
}
}
catch
{
Response.Write("The file could not be written:");
}
這做法用迴圈替換,標記數量多時速度依然很快,模板也交給了設計人員維護。實務上還要補兩件事:寫檔時指定完整實體路徑並確認 ASP.NET 帳號有寫入權限,以及對要填進模板的使用者輸入做編碼,避免把不受控的內容直接寫進靜態檔。