ASP 原生 <!--#include file="inc.asp"--> 在編譯階段靜態處理,無法用變數動態決定檔案路徑。常見變通方案是用 FileSystemObject 讀取檔案內容,再用 Execute 執行,但會遇到巢狀 include 無法解析的問題。
以下函式支援:
<!--#include ...--> (傳統靜態 include)<%=expr%> 轉為 Response.Write expr 相容執行ExecuteFunction IncludeConvert(oRegExp, strFilename, strBlock)
Dim incStart, incEnd, oMatches, match, str, code
code = ""
incEnd = 1
incStart = InStr(incEnd, strBlock, "<!--#include ") + 13
Do While incStart > incEnd + 12
' 輸出 include 標籤前的純 HTML/文字
str = Mid(strBlock, incEnd, incStart - incEnd - 13)
str = EscapeForResponseWrite(str)
code = code & vbCrLf & "Response.Write " & Chr(34) & str & Chr(34)
' 解析 include 檔名
incEnd = InStr(incStart, strBlock, "-->") + 3
oRegExp.Pattern = "(\w+)=[""']([^""']+)[""']"
Set oMatches = oRegExp.Execute(Mid(strBlock, incStart, incEnd - incStart - 3))
Set match = oMatches(0)
' match.SubMatches(1) 為檔名
Dim subPath
subPath = Mid(strFilename, 1, InStrRev(strFilename, "/")) & match.SubMatches(1)
' 遞迴處理子檔案
code = code & Include(subPath)
incStart = InStr(incEnd, strBlock, "<!--#include ") + 13
Loop
' 處理尾部剩餘內容
str = Mid(strBlock, incEnd)
str = EscapeForResponseWrite(str)
code = code & vbCrLf & "Response.Write " & Chr(34) & str & Chr(34)
IncludeConvert = code
End Function
Function EscapeForResponseWrite(str)
str = Replace(str, Chr(34), Chr(34) & Chr(34)) ' 雙引號跳脫
str = Replace(str, vbCr, "")
str = Replace(str, vbLf, "")
str = Replace(str, vbCrLf, "")
EscapeForResponseWrite = str
End Function
Function Include(filename)
Dim re, content, fso, f, aspStart, aspEnd, code
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(Server.MapPath(filename))
content = f.ReadAll
f.Close: Set f = Nothing: Set fso = Nothing
code = ""
aspEnd = 1
aspStart = InStr(aspEnd, content, "<%") + 2
Set re = New RegExp
re.Pattern = "^\s*=" ' 處理 <%= ... %>
Do While aspStart > aspEnd + 1
' 先處理 ASP 區塊前的靜態內容 (可能含 #include)
code = code & IncludeConvert(re, filename, Mid(content, aspEnd, aspStart - aspEnd - 2))
' 處理 ASP 程式碼區塊
aspEnd = InStr(aspStart, content, "%>") + 2
code = code & vbCrLf & re.Replace(Mid(content, aspStart, aspEnd - aspStart - 2), "Response.Write ")
aspStart = InStr(aspEnd, content, "<%") + 2
Loop
' 處理最後一段靜態內容
code = code & IncludeConvert(re, filename, Mid(content, aspEnd))
Set re = Nothing
Include = code
End Function
<%
' 主程式
Dim mainCode
mainCode = Include("templates/header.asp") ' 回傳合併後程式碼字串
Execute(mainCode) ' 實際執行
%>
IncludeConvert 展開,再處理 <% ... %> 程式碼區塊。InStrRev(filename, "/") 取得父目錄,確保巢狀 include 能正確解析相對路徑。Response.Write "..." 語法合法。^\s*=\s* 偵測 <%=expr%> 並轉為 Response.Write expr;(\w+)=["']([^"']+)["'] 解析 file="..." 或 virtual="..."。Execute 執行的動態程式碼錯誤行號會指向動態字串,除錯較困難。若專案允許升級,建議改用:
UserControl、Partial View、RenderPartial 原生支援動態載入。透過 FileSystemObject + 正則解析 + Execute 組合,可突破傳統 #include 的靜態限制,實現支援巢狀包含的動態模板系統。但需權衡效能、安全性與維護性,現代專案建議評估遷移至支援原生動態組合的架構。