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.QueryString("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, if you are still using IIS 4.0, BOTH include files will be processed (IIS 5.0 is much smarter about this). So, the more options you have, the less efficient this solution will be. When the number of possible includes start getting a bit high, and the code in the include files is pure HTML (no ASP logic), you could try something like this:
<% if Request.QueryString("param")="2" then filespec = "2.htm" else filespec = "1.htm" end if filespec = Server.MapPath(filespec) set fs = CreateObject("Scripting.FileSystemObject") set f = fs.OpenTextFile(filespec) content = f.ReadAll() set f = nothing set fs = nothing Response.Write(content) %> | (If the file has ASP logic, it will be displayed as plain text, because it won't be available to the ASP engine early enough.) Another option, in IIS 5.0 and up, is to use "dynamic includes" via Server.Execute. Using the above scenario, here is an example:
<% if Request.QueryString("param")="2" then Server.Execute("2.htm") else Server.Execute("1.htm") end if %> | Please see Article #2006 for some of the common problems people have with the the Server.Execute and Server.Transfer methods.
[ Comment, Edit or Article Submission ]
Share this:
More about:
| Nov |
December 2008 |
Jan |
| Sun |
Mon |
Tue |
Wed |
Thu |
Fri |
Sat |
| |
1 |
2 |
3 |
4 |
5 |
6 |
| 7 |
8 |
9 |
10 |
11 |
12 |
13 |
| 14 |
15 |
16 |
17 |
18 |
19 |
20 |
| 21 |
22 |
23 |
24 |
25 |
26 |
27 |
| 28 |
29 |
30 |
31 |
|
|
|
|
|
|
|