Including a file in a ASP page

Using includes What’s a include file? An include file is just an ASP page that’s called from another page:

<!–#include file=”myincludefile.asp” –>

You would include the code above in your ASP page, like this:

page1.asp

<HTML><HEAD>
<TITLE>MY PAGE</TITLE>
</HEAD><BODY>
<!–#include file=”myincludefile.asp” –>
</BODY></HTML>

Make sure both of your pages are of an .asp extension.

Your include file could include anything:

myincludefile.asp

<%
Response.Write “Welcome! Today’s date is “ & Now
%>

This would turn your first page into this:

<HTML><HEAD>
<TITLE>MY PAGE</TITLE>
</HEAD><BODY>
<%
Response.Write “Welcome! Today’s date is “ & Now
%>
</BODY></HTML>

So why use an include file? Why not just add the following code into your page directly? In this instance, it would be easier. However, what if you had a large web site that had copyright information on every page and you needed to change it. Well, if you didn’t use a include file, you would have to change every page, which could be time consuming. If you used an include file, you would only have to change that file. Instantly, you can see the benefits of using a include file.

Now you don’t just have to have an .asp extension for your include file. You can have an .htm, .html, .inc and among many more extensions.

*Remember, if you use a .htm, .html or .inc extension, people can view the source code. To be safe, stick with an .asp extension.

What if you have a file located somewhere other than the directory your in? You can use the following code:

<!–#include virtual=”myincludefile.asp” –>

As you can see, instead of <!–#include file, we are now using <!–#include virtual. This is allowing us to start in our root directory. This piece of code above will include the file myincludefile.asp that’s located in your root directory. If your include file is in a folder named includes, your code would look like this:

<!–#include virtual=”includes/myincludefile.asp” –>

Using variables in your include file

Say you need the same format on top of every page in your web site; however, the title needs to be different. You could do the following:

page1.asp

title = “My Index Page”
<!–#include file=”includes/myincludefile.asp” –>
<p align=”center”>Welcome to my web site</p>
</BODY></HTML>

myincludefile.asp

<HTML><HEAD>
<TITLE><%= title %></TITLE>
</HEAD><BODY>

This would turn your first page into this:

title = “My Index Page”
<HTML><HEAD>
<TITLE><%= title %></TITLE>
</HEAD><BODY>
<p align=”center”>Welcome to my web site</p>
</BODY></HTML>

All this does is create a variable named title which you would want in every page. The include file then is added to page1 and pulls that variable and uses it for it’s title.

So as you can see, using includes can be very useful in certain circumstances.

Author: Andrew Schools