早期 ASP.NET WebForms 時代常用模板替換產生靜態 HTML,現代專案推薦使用 RazorEngine 或 Scriban 等成熟模板引擎。本文展示傳統字串替換法與 RazorEngine 兩種實作,並比較優劣。
<!DOCTYPE html>
<html>
<head><title>$title$ 靜態頁 Demo</title></head>
<body>
<table width="100%" border="0" bgcolor="#339900">
<tr><td height="34" align="center" bgcolor="#FFFFFF"><span class="STYLE1">$title$</span></td></tr>
<tr><td height="42" bgcolor="#FFFFFF">內容:$content$</td></tr>
</table>
</body>
</html>
public static string GenerateStaticPage(string templatePath, string title, string content)
{
string template = File.ReadAllText(templatePath);
string html = template
.Replace("$title$", title)
.Replace("$content$", content);
return html;
}
// 使用
string html = GenerateStaticPage("template.html", "產品介紹", "這是詳細內容...
");
File.WriteAllText("product.html", html, Encoding.UTF8);
Install-Package RazorEngine.Core
@model dynamic
<!DOCTYPE html>
<html>
<head><title>@Model.Title 靜態頁 Demo</title></head>
<body>
<h1>@Model.Title</h1>
<div>@Raw(Model.Content)</div>
@if (Model.ShowFooter)
{
<footer>@Model.FooterText</footer>
}
</body>
</html>
using RazorEngine;
using RazorEngine.Templating;
public static string RenderRazorTemplate(string templatePath, object model)
{
string template = File.ReadAllText(templatePath);
return Engine.Razor.RunCompile(template, "templateKey", null, model);
}
// 使用
var model = new
{
Title = "產品介紹",
Content = "這是詳細內容...
",
ShowFooter = true,
FooterText = "© 2024 Company"
};
string html = RenderRazorTemplate("template.cshtml", model);
File.WriteAllText("product.html", html, Encoding.UTF8);
| 維度 | 字串替換 | RazorEngine |
|---|---|---|
| 依賴 | 無 | NuGet 套件 |
| 邏輯支援 | 無 (純替換) | 完整 C# (if/foreach/func/partial) |
| 佈局/區塊 | 不支援 | 支援 @RenderBody, @RenderSection |
| 編譯檢查 | 執行時才知錯誤 | 編譯時檢查 (VS IntelliSense) |
| 效能 | 極快 | 首次編譯較慢,後續快取極快 |
| 適用場景 | 極簡單、無邏輯、零依賴需求 | 複雜報表、郵件模板、CMS 靜態化 |
// NuGet: Scriban
using Scriban;
var template = Template.Parse(File.ReadAllText("template.scriban"));
string html = template.Render(model); // model 為 anonymous object 或 ScriptObject
Scriban 語法類似 Liquid/Jinja2,無需編譯 IL,適合 .NET Native/AOT、Source Generator 場景。
Parallel.ForEach) 提升吞吐量。選對模板引擎,讓靜態頁面產生從「字串拼湊」進化為「結構化開發」,可維護性與擴展性雙贏。