GuidesTo include or not to include

To include or not to include

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.




by Aaron Bertrand

One of the greatest obstacles faced by ASP developers is
the ability to dynamically include files. Since #include
directives are processed BEFORE the ASP code, it is impossible
to use if/else logic to include files.
One of the greatest obstacles faced by ASP developers is
the ability to dynamically include files. Since #include
directives are processed BEFORE the ASP code, it is impossible
to use if/else logic to include files.

Or is it?

Depending on what you are doing within your include files,
and how many you are including, it IS possible to use if/then
logic to make use of includes. While it is not feasible for
all situations, and it is often an inefficient solution, it
can occasionally be quite a handy workaround.

Let’s start with two sample HTML files, 1.htm and
2.htm. For the sake of simplicity, they contain very
simple code:

    This is 1.htm

    This is 2.htm

Now, let’s set up some conditional includes! For this
example, we’ll assume you want to include the file
2.htm if your page is passed a parameter of 2,
otherwise include 1.htm. Here is an example of how you
could accomplish this task:

      

      

Now try accessing the page in these three ways, and
experiment with the results:

    http://yourserver/file.asp?param=1
    http://yourserver/file.asp?param=2
    http://yourserver/file.asp

Of course you can perform this kind of include logic based
on various conditions, such as the date, the time, or the
user’s browser.

Please note that in the above example, BOTH include files
are processed. So, the more options you have, the less
efficient this kind of solution will be. When the number of
possible includes start getting a bit high, you could try
something like this:

    if request(“param”)=”2″ then
      filespec =
    “2.htm”
    else
      filespec = “1.htm”
    end
    if

    filespec = server.mapPath(filespec)
    scr =
    “scripting.fileSystemObject”
    set fs =
    server.createobject(scr)
    set f =
    fs.openTextFile(filespec)
    content = f.readall
    set f
    = nothing
    set fs = nothing

    response.write(content)
    %>

The FileSystemObject is useful for many things, and it fits
into the dynamic include paradox quite nicely.

🙂

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories