Dynamic Includes

Homepage > ASP Tutorials > Dynamic Includes

What if you want a dynamic include file based on a users preference? For example, you might want to allow the user to select a different coloured page template. For this tutorial let's assume that you already have the users colour preference stored in a cookie called "Color":

sColor = Request.Cookies("Color")
<!--#include virtual="/<%=sColor%>.asp"-->

But... this code won't work. This is because include files are attached before the ASP is processed.

So how do we work around this?

if...else dynamic include

The easiest way is to use an if...else statement to select a file:

<% if sColor = "Red" then %>
<!--#include virtual="/red.asp"-->
<% elseif sColor = "Green" then %>
<!--#include virtual="/green.asp"-->
<% else %>
<!--#include virtual="/blue.asp"-->
<% end if %>

All three files are included server-side, but since each include file is inside the if...else statement, only one of the files code is processed and sent to the browser.

We could achieve the same result using a Select Case statement, which looks a little tidier:

<% select case sColor
	case "Red" %>
<!--#include virtual="/red.asp"-->
<%	case "Green" %>
<!--#include virtual="/green.asp"-->
<%	case "Blue" %>
<!--#include virtual="/blue.asp"-->
<% end select %>

Related links

Rate this tutorial!

  • Currently -25186.1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Rated -25186.1/5 stars (397 votes cast)

Make an enquiry

Privacy policy