next up previous contents
Next: Combo Forms Up: Perl on the Web Previous: Fill-out Forms   Contents


HTML Helper methods in the CGI module

The available helper methods are summarized in Table [*]. Each of the methods generates a tag based on the method's name, and processes arguments as explained in the next paragraph. Remember that all these methods return a string containing the necessary HTML code, and must be printed in order to be made visible on a user's browser.


Table: HTML helper methods
Method Function Arguments/Comments
a anchor href,name
b boldface  
center Centering output  
br linebreak Use in place of \n
em emphasis  
h1 Headings also h2,...,h6
hr Horizontal Rule align,width
img Images src,align,alt
li List items  
ol Start ordered list  
p Paragraph  
table Start a table align,border
td Table data align,colspan,valign
th Table headings  
Tr Table row align,valign (note capital T)
ul Start bullet list  


When you call any of the methods in Table [*] with no argument, they generate only the corresponding tag. If you call any of the methods with a single scalar argument, they will generate both the appropriate start and end tags around that argument; with multiple scalar arguments it concatenates the arguments and then surrounds them with the appropriate tags.

Perhaps the most interesting feature of the helper methods is that when they are passed a reference to an array (or an anonymous array), the will distribute the start and end tags over each element of the array. This feature is especially useful for lists and tables.

Consider producing HTML for a table containing the names of animals. Using the distributive feature of the helper methods, we could write:

print $q->ul($q->li(['dog','cat','chicken','duck','goose']));
which will generate the following HTML code, reformatted for easier reading.
     <UL><LI>dog</LI> <LI>cat</LI> <LI>chicken</LI> 
         <LI>duck</LI> <LI>goose</LI></UL>

The distributive feature also makes producing HTML tables simple. Suppose we have a file containing names, room numbers and email addresses for employees, separated by tabs, and we wish to generate a table of those values. The helper methods could be used as follows:

     while(<FILE>){
          @info = split("\t");
          push @rows, $q->td(\@info);
     }
     
     print $q->table($q->Tr(\@rows));

Finally, if the first argument to the helper methods is a reference to a hash (or an anonymous hash), the named elements are used as arguments to the tag in question. Furthermore, if the technique of the previous section using array references is followed, those arguments are further distributed over the tags. So to center the text in all of the cells of the previous table, we could modify the call to the td method as follows:

     push @rows, $q->td({align=>'center'},\@info);


next up previous contents
Next: Combo Forms Up: Perl on the Web Previous: Fill-out Forms   Contents
Phil Spector 2002-10-18