America's Town Square
More Free Stuff

Spice Up Your HTML Pages with Random Widgets

A Free Link to Your Random Widgets, What is a Random Widget?,
Examples applications, Server Side Includes, Storing Your Widgets,
Widget Files, Widget Arrays, A Perl for Every Page,
Bring it all Together, Download widgets.pl now, Epilogue

A free link to your random Widgets

If you decide to use random widgets, please let us know where and how and we'll include a description of your use and a link to your page.

What is a Random Widgets?

Widgets, widgets, everyone loves random widgets...well at least most people like widgets. A widget might be almost anything. The basic idea is to select an item a random and have it display somewhere in your HTML document.

Use a widget generator to insert a random thought for the day in your Web home page. Or, insert a tip for the current session. You can get really creative and change the look and feel of your page every time some enter your inner sanctum by selecting from a group of body tags.

No matter what kind of random widget you use, the underlying concept is the same. Generate a random number and select a widget corresponding to the number. First a word of caution.

You must have access to Server Side Includes (SSI)

Before you get carried away with creativity, check with your Internet Service Provider as see if they allow cgi scripts in general and server executable side includes specifically. At the heart of random Widgets is a line in your HTML document looking something like the following.:
<!--#exec cgi="/cgi-bin/thoughts.pl"-->
The America's Town Square home page has two of these widget generators, one for tips and one for a "Not so serious thought." You would insert the following at the point you want the random thought:
</FONT><FONT SIZE=6 COLOR=YELLOW>On a not so serious note...</FONT>
<FONT SIZE=+1>
<PRE>
<!--#exec cgi="/cgi-bin/thoughts.pl"-->
</PRE></FONT>
The PRE tags are to preserve the line breaks in the text file holding the thoughts. The path to your Perl script may need modification based upon your provider's configuration.

The use of SSI put additional demands on a Web server. When a server is SSI enabled, there is extra processing required to parse the served document. Many servers can be configured to parse only those HTML document containing the extension "shtml". Again, check with your Internet Service Provider to determine if they require the shtml extension on documents contain server side includes.

Storing Your Group of Widgets

There are two ways of storing your group of widgets:
  1. In an array within the script itself.
  2. In a file associated with the script.
The use of an array is more efficient since the script does not have to read a file. However, array storage tends to be somewhat tedious to maintain as compared to a plain text file. As you'll see in a minute, entering and maintaining array constants tend to be somewhat tedious. Most people choose an external file to hold their widgets, especially for fairly large numbers of widgets. Let's first take a look at file construction.

Widget Files

Widget files take the form of a group of widgets separated by some type of delimiter. I delimiter is a character, or group of characters, that would NEVER appear within the list of widgets. Let's take a look at a portion of the file used to generate the "Not so serious thought" and the ATS home page.
Computers in the future may weigh no more than 1.5 tons.
--Popular Mechanics magazine,  1949. 
(1)
Clothes make the man.  
Naked people have little or no influence on society.
-- Mark Twain
(1)
The gene pool could use a little chlorine.
(1)
It isn't necessary to be
   rich and famous to be happy....
It's only necessary to be rich.
--Alan Alda
(1)
It this case the delimiter is "(1)" (without the quotes.) Adding is new thought -- or any other widget -- is simple: If you are automating the process and using a form/script to add new widgets, you will append to the end of a file. In this case, insert the delimiter before the new widget.

The widgets can be any size. If you actually display the widgets between the PRE tags, the individual line formatting will be preserved. You can use any delimiter you prefer, just make sure they are all exactly the same and additionally, make sure the delimiter never appears within the body of a widget.

Widget Arrays

As mentioned above, storing widgets in an array in within script itself is very efficient since the script does not have to read an external file. In programming parlance, an array is a grouping of similar "things," in this case widgets.

A creative use of the widget concept is to store a small group of body tags in an array. When executed by your HTML document the script produce a different look and feel for the same page. The effect can be quite impressive. Be prepared to answer "how did you do that" questions.

In the following code snippet, the array @body is loaded with the various body tags. In Perl, a single array element is referenced as a scalar variable with a subscript enclosed between the "[]" pair. The first element in an array is designated [0]. (We computer types don't waste numbers.) The first element of array @body would therefore be, $body[0], the second $body[1], and so on. Here is a set of four different body tags. The third tag is just the plain old body tag.


$body[0] =  # Blue from main index page
"<BODY BGCOLOR=\"01017E\" TEXT=\"FFFFFF\" VLINK=\"FF0000\" LINK=\"FFFF00\">";
$body[1] =  # Red from what's hot
"<BODY BGCOLOR=\"8B0518\" TEXT=\"FFFFFF\" LINK=\"FFFF55\" VLINK=\"0000FF\">";
$body[2] = "<BODY>"; # Default colors
$body[3] =  # Teal background
"<BODY BGCOLOR=\"007070\" TEXT=\"FFFFFF\" LINK=\"FF0000\" VLINK=\"FFFF00\">";
Make sure your choice of text and link colors work together. If you simply select a background color at random you run the danger of selecting a black background using black text. Makes the page difficult to read.

An example of changing background colors can be found on the LBI & Ocean County, NJ Online home page. There are two other random Widgets on the page, an entry from the guest book and one the URL hall of fame.

A Little Perl for Every Page

Let's look at little snippets of Perl code. I'm making the assumption your host server is using Unix. If not, check with one of your local gurus for tweaking. If you're still with me at the end of this tutorial, you can download the entire script.

The first line in any Perl script must let Unix know this is a Perl script, not a shell script. It contains the path to Perl on your system and my be different than what is show below. You can check your path to Perl using the Unix "which" command. At the Unix prompt, enter:

which perl

Enter the following line starting with the "#!" and your path to Perl.

#!/usr/bin/perl

The script next informs the server what is about to be sent.

print "Content-type: text/plain\n\n";

Next, some system constants.

# Script variables, change if assumptions are wrong.
$WidgetDelimiter = "\\(1\\)"; # Assumes widgets are separated by (1)
$WidgetExtension = ".txt";    # Assumes widget file extension of txt
$WidgetPath      = "data/";   # Assumes path data under the script path
The above constants assume your widgets are delimited by (1), the widget file has an extension of "txt" (lower case) and the widget file is in a directory named data which is a subdirectory of the directory holding the script. You cannot have the text file in a directory where the server expects to find executable cgi scripts.

I'm now going to get cute. I like to have my scripts serve multiple masters. The widgets.pl script will word for different HTML documents. If an HTML document is name tips.html, the script will look for a widget file name tips.txt. If the HTML file is thoughts.html, the script will look for thoughts.txt. There are several advantages to doing this. If you want to make a change to the script, you only have to do it in one place.

The next few lines accomplish the widget naming task. If you don't want to use this extraordinarily creative scheme, simply comment (#) out the first group of statements and hard code you file name in the last statement.

$WidgetFile = $ENV{'DOCUMENT_URI'}; # Get name of calling HTML file
$_ = $WidgetFile;                   # Set up for regular expression
$WidgetFile =~ m!.*/(.*)\.!;        # Put extensionless file name in $1
# Add "data/" to path and ".txt" to file name
$WidgetFile = "$WidgetPath$1$WidgetExtension";        
The next group of instructions open the widget file, transfer it to the @widget array (each line is an element), and then put it all into one big scalar variable ($bigdata).
open(WIDGET, "$WidgetFile") ||      # Open the file
  die "Cannot open $WidgetFile\n";  # Bummer if you get here
@widget  = ;                # Read up file into array
$bigdata = join("",@widget);        # Transfer file to scalar variable
Now, place each individual widget into an element of array @widget and count the number of elements.
@widget = split(/$WidgetDelimiter/,$bigdata);  # Break widgets into array
$WidgetCount= @widget;              # Number of widget elements
Moving right along, seed the random number generator and generate a random number. The Perl rand(range) function returns a random number between 0 and range minus one. If range is 4, rand will return a random number greater than or equal to zero and less than 4. This is exactly what we want since an array with four elements will be subscripted by [0], [1]. [2], and [3]. The int function removes the fraction portion of the random number.
srand();  # Seed random number generator
$WidgetIndex = int(rand($WidgetCount)); # Get random number for array
And now, a little drum roll, display the widget.
print "$widget[$WidgetIndex]";      # Display the random widget

Bringing it all Together

Lets bring it all together. Take the following steps:
  1. Create a file containing your widgets.
  2. If you don't already have one, create a directory /data/ under your cgi-bin directory. (The cgi-bin directory may have a different name on your provider's system.
  3. Transfer widgets.pl to your cgi directory. (If you first transfer it to your PC, make sure it's in Unix format in your cgi directory. (Edit the file and back up over the DOS end of file marker.)
  4. Make it executable by entering chmod 755 widgets.pl (775 on some servers) at the Unix prompt while the directory containing widgets.pl is your working directory.
  5. Insert the Server Side Include line
    <!--#exec cgi="/cgi-bin/widgets.pl"-->
    in the HTML document that will display the widget. You will of course substitute your path instead of mine.

Download the Perl Script widgets.pl

Click on the next link to display widgets.pl. If you want to save it, drop your browser's File menu, select Save As, and pick a directory on your PC.

Download widgets.pl now

Epilogue

I would appreciate any feed back you care to offer on this tutorial. Don't forget to let me know if you use a random widget so we can give you a free link. Also, let me know what else you would like to see on these pages.

Thanks,
Urb LeJeune president America's Town Square.

Random Widget Examples

The America's Town Square Home Page has three random widgets. The first selects a BODY tag from a group of five. causing random display of the background color and the color of the links. In addition, there are random technical "Tip of the Day" and a Not So Serious Thought of the Day. Nice effects to give the feeling of change.

I Love Atlantic City Online has two random widgets on their Home Page. The page has a section called Spotlight. First, a random selections from the Self-Updating Guest Book. Next a random selection from the I Love Atlantic City user-supplied URL Hall of Fame. The possibility of having a guest book or hall of fame entry displayed on the home page is a big participation inducement to visiting surfers.

Please subscribe to the free ATS Newsletter so we can keep you
up to date with our "free stuff", special offers, and other goodies.

Back to the ATS Home Page

Please sign our self-updating guestbook

How about some free stuff from ATS?

Please send our crotchety Webmaster some mail.
Copyright ©1996 America's Town Square
15 Hunter Drive
Tuckerton, NJ 08087
(609) 294-0320 [an error occurred while processing this directive]