dcsimg

To include or not to include

By ServerWatch Staff (Send Email)
Posted Apr 6, 1999


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:

    <!-- 1.HTM: -->

    <font color=#ff0000>This is 1.htm
    </font>

    <!-- 2.HTM: -->

    <font color=#0000ff>This is 2.htm
    </font>

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:

    <% if request("param")="2" then %>

      <!--#include file="2.htm"-->

    <% else %>

      <!--#include file="1.htm"-->

    <% end if %>

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.

:)

Page 1 of 1


Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.


 

 


Thanks for your registration, follow us on our social networks to keep up-to-date