ASP #include

服务器端包含的语法、virtual 与 file 的区别、常见用法与坑。

Beginner
Key Points#include 在脚本执行前把文件内容原样插入,所以被包含的文件不能有重复的 <% @ %> 指令。

两种写法

ASP
<!-- #include virtual="/includes/header.asp" -->
<!-- #include file="header.asp" -->
FormPath baseUse when
virtual站点根目录跨目录引用,最常用
file当前文件所在目录同目录下的片段
file="../x"需要开启「启用父路径」尽量避免

virtual with a leading / is rooted at the site and most stable; file uses relative paths that break when a file moves. ../ under file also needs "Enable Parent Paths" in IIS, which is off by default.

典型结构

Text
/includes/
├── header.asp        ← 页头:logo、导航
├── footer.asp        ← 页脚:版权、备案
└── conn.asp          ← 数据库连接串
/default.asp
/products/list.asp
ASP
<%-- default.asp --%>
<!-- #include virtual="/includes/header.asp" -->

<main>
  <h1>首页</h1>
</main>

<!-- #include virtual="/includes/footer.asp" -->

被包含文件里不能有什么

ASP
<%-- includes/header.asp:不要写 @ 指令 --%>
<%
    ' 只写片段逻辑
    Dim siteName
    siteName = "我的站点"
%>
<header>
  <a href="/"><%= siteName %></a>
</header>

Directives like <%@ Language %> may appear only once after merging; repeating them in an included file raises a duplicate-directive error. Keep all directives in the main file.

常见坑

  • 变量重复声明 —— 两个片段都 Dim conn,合并后报「名称重定义」
  • 输出在 include 之前 —— 有任何字节输出,Response.Redirect 就失效
  • UTF-8 BOM —— 被包含文件带 BOM 会往响应里塞字节
  • 改了没生效 —— IIS 缓存了编译结果
Included files must be UTF-8 without BOM. With a BOM those three bytes precede all output, after which Response.Redirect and Response.Cookies fail silently — very time-consuming to diagnose.

包含 vs 函数库

ASP
<%-- includes/funcs.asp:只放函数,不放输出 --%>
<%
    Function SafeText(s)
        SafeText = Server.HTMLEncode(s)
    End Function

    Function Money(v)
        Money = FormatNumber(v, 2)
    End Function
%>
ASP
<%-- 页面顶部引入函数库 --%>
<!-- #include virtual="/includes/funcs.asp" -->
<%
    Response.Write Money(1234.5)
%>
Output
1,234.50

Collect helpers in one funcs.asp and include it everywhere — less chance of forgetting Server.HTMLEncode than typing it by hand. Keep output fragments (header/footer) separate from logic fragments (helpers).

Friends & Partners