Using Includes
The previous FAQ discussed the importance of using functions in your ASP
to modularize your code. Unfortunately, a function written in one ASP
file cannot be accessed by a separate ASP file. That is what includes are
useful for (among other things).
Includes are similar to #include's in C++, or
uses in Pascal. An include in ASP simply copies over the
text from the specified file into the current file. For example, say you
had a file named PrintHelloWorld.asp, which had the following code:
<%
Response.Write("Hello, world!")
%>
Now, we can include that code in another ASP file.
<%@ LANGUAGE="VBSCRIPT" %>
<HTML>
<BODY>
<!--#include file="PrintHelloWorld.asp"-->
</BODY>
</HTML>
This HTML file will output "Hello, World" to the client's browser screen.
By using the include file, it was as if we had just typed the text from
the file PrintHelloWorld.asp directly into the above source code.
To include a file, the syntax is like an HTML comment. You need the
<!--, followed by a #include. You can then use one or two
keywords, either file or virtual. What one you
use depends on the location of the file you want to include relative to
the current file. If the file you want to include is in the same
directory or a subdirectory of where the current file is, use the
file keyword, like we did in the example above.
If, however, the file is in a different directory altogether, you need to
use virtual. For example, it could look like this:
<!--#include virtual="/scripts/PrintHelloWorld.asp"-->
or
<!--#include virtual="../ASPDirectory/PrintHelloWorld.asp"-->
Let's look at one more quick example of #include's. Imagine
that we have a file in our scripts directory named SquareFunction.asp. In
this file, we have an ASP function that will square a number. Here is
what the file SquareFunction.asp would look like:
<%
function Square(num)
Square = num * num
end function
%>
Now, if we have an ASP page that we want to use the square function, we
would simply type the following code:
<%@ LANGUAGE="VBSCRIPT" %>
<!--#include virtual="/scripts/SquareFunction.asp"-->
<%
Dim MyAge
MyAge = CInt(20)
%>
<HTML>
<BODY>
Scott is <%=MyAge%> years old.
But he feels as if he's <%=Square(MyAge)%>!
</BODY>
</HTML>
Note that it was if we had typed in the file SquareFunction.asp into the
ASP file above. The use of include files in ASP is good programming
technique, for it allows one copy of source code to be used multiple
times. You should strive to write your ASP applications as modular as
possible, and include files help you do just that!