萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 動態包含檔案進階技巧:支援巢狀 #include 與 Execute 執行

痛點:傳統 #include 無法動態決定

ASP 原生 <!--#include file="inc.asp"--> 在編譯階段靜態處理,無法用變數動態決定檔案路徑。常見變通方案是用 FileSystemObject 讀取檔案內容,再用 Execute 執行,但會遇到巢狀 include 無法解析的問題。

改進版動態包含函式

以下函式支援:

  • 遞迴解析被包含檔案中的 <!--#include ...--> (傳統靜態 include)
  • 正確處理相對路徑
  • 將 <%=expr%> 轉為 Response.Write expr 相容執行
  • 回傳完整合併後的 ASP 程式碼字串,最後再 Execute
Function 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) ' 實際執行
%>

關鍵設計細節

  1. 雙階段解析:先把靜態區塊 (含 #include) 透過 IncludeConvert 展開,再處理 <% ... %> 程式碼區塊。
  2. 路徑解析:用 InStrRev(filename, "/") 取得父目錄,確保巢狀 include 能正確解析相對路徑。
  3. 字串跳脫:靜態內容輸出時需將雙引號加倍、移除換行,確保產生的 Response.Write "..." 語法合法。
  4. 正則表達式:^\s*=\s* 偵測 <%=expr%> 並轉為 Response.Write expr;(\w+)=["']([^"']+)["'] 解析 file="..." 或 virtual="..."。

限制與注意事項

  • 效能:每次請求都讀檔、解析、Execute,高流量網站建議快取編譯結果 (Application 變數或檔案快取)。
  • 錯誤行號:Execute 執行的動態程式碼錯誤行號會指向動態字串,除錯較困難。
  • 安全性:嚴禁包含使用者可控路徑的檔案,防止任意檔案讀取/執行攻擊。
  • 編碼:確保所有 .asp 檔案編碼一致 (建議 UTF-8 with BOM 或 ANSI),避免中文亂碼。

現代替代方案

若專案允許升級,建議改用:

  • ASP.NET:UserControl、Partial View、RenderPartial 原生支援動態載入。
  • Classic ASP + JSON/Template Engine:前後端分離,ASP 僅輸出資料,前端 JS 渲染模板。
  • Server.Execute / Server.Transfer:內建方法可呼叫其他 .asp 頁面並共享內建物件,但無法像 include 那樣內嵌於當前頁面流程中。

總結

透過 FileSystemObject + 正則解析 + Execute 組合,可突破傳統 #include 的靜態限制,實現支援巢狀包含的動態模板系統。但需權衡效能、安全性與維護性,現代專案建議評估遷移至支援原生動態組合的架構。

copyright © 萬盛學電腦網 all rights reserved