Include files in ASP and their syntax

A block of ASP code in one script can be inserted into an another script, and this is an include file. It is a very powerful method of repeating code and, more importantly, keeping repeated code in one place so that it can be easily modified. An include file might be used to define variables or constants that are used throughout an ASP application. They might be used to contain functions that are used in a website. They are frequently used to define the connection parameters for a database. They can also be used to contain HTML such as menus, or page headers and footers so that an edit to one file updates the entire site.

Code to call an include file

The include file is called using the include directive, which is written as an HTML comment, not inside the ASP <% %> code. The include file can be either an absolute path or a virtual path.

<!-- #include file="include.asp" -->

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

An include file can have the extension .inc but .asp is usually preferred because if it is called directly it will execute and cannot be viewed by the user.

The include file itself

The include file is a normal ASP file complete with <% at the start and %> at the end, if it contains executable code. It must not contain the <%@ at the beginning because this must only appear once and it should be in the main script. It can just be some HTML code with the .asp extension and this will appear in the page in place of the include directive.

Notes:

The sample code in these tutorials is written for VBScript in classic ASP unless otherwise stated. The code samples can be freely copied.