首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> ASP 程式設計 >> ASP 基礎

ASP #include 指令:模組化重複使用程式碼

     編輯:ASP 基礎

ASP #include 指令:在執行前插入外部檔案內容


指令用途

  • 共用函式庫、類別定義
  • 頁首/頁尾版權資訊
  • 資料庫連線設定
  • 任何多頁重複使用的程式碼片段

語法與關鍵字

<!--#include virtual="/virtual/path/file.inc"-->  <!-- 從虛擬目錄根目錄起算 -->
<!--#include file="relative/path/file.inc" -->   <!-- 相對於目前檔案目錄 -->

virtual:以網站虛擬目錄為起點 (如 /includes/header.inc)
file:相對路徑 (如 ../common/config.inc),不得使用 .. 跳出網站根目錄。


完整範例

主頁面 mypage.asp

<!DOCTYPE html>
<html>
<body>
<h3>名言精選:</h3>
<p><!--#include file="wisdom.inc"--></p>
<h3>目前時間:</h3>
<p><!--#include file="time.inc"--></p>
</body>
</html>

wisdom.inc

"One should never increase, beyond what is necessary,
the number of entities required to explain anything."

time.inc

<%
Response.Write(Time)
%>

瀏覽器實際接收的 HTML

<!DOCTYPE html>
<html>
<body>
<h3>名言精選:</h3>
<p>"One should never increase, beyond what is necessary,
the number of entities required to explain anything."</p>
<h3>目前時間:</h3>
<p>11:33:42 AM</p>
</body>
</html>

重要限制與最佳實務

  • 處理時機:在腳本執行前由伺服器展開插入,因此不能在腳本區塊 <% %> 內使用變數決定檔名。
  • 錯誤寫法:
    <%
    fname = "header.inc"
    %>
    <!--#include file="<%fname%>"-->  <!-- 無效 -->
  • 迴圈中包含:不可直接在 <% %> 迴圈中放置 include,需拆分腳本區塊:
    <% For i = 1 To n %>
    <!--#include file="count.inc" -->
    <% Next %>
  • 副檔名建議:包含敏感資料 (連線字串、密鑰) 的 include 檔請用 .asp 副檔名,避免被直接瀏覽下載。.inc 檔若被直接請求會以純文字顯示內容。
  • 巢狀包含:include 檔可再包含其他檔案,同一檔案可被多次包含。

現代替代方案

ASP.NET 使用 User Control (.ascx)、Master Page、Partial View (MVC/Razor Pages) 或 Tag Helpers (Core) 實現更強型別、支援設計時期驗證的模組化重用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved