Article

Embedding Perl Into Web Pages

Page: 1 2 3 4 5 6 7 8 9 10 11 Next

If we place this file, say environ1.html, in the directory specified by the /mason location in httpd.conf, and call it with http://localhost/mason/environ1.html, the following results are obtained:

518masonexample

The various sections of the file are described below:

  • The <%perl>...</%perl> section is used for a block of Perl code. In it we declare the variables $col1 and $col2.
  • After this, we give the level 2 heading using the variable $headline, which is initialized in the <%init>...</%init> block (this is executed as soon as the component is loaded). Note the use of <%...%> to echo the value of $headline within a line of HTML code.
  • Next we set up the table used to print out the values of the environment variables. Headings for this table use the component .bgcolor (note the convention of using a leading period in defining component names). Components are called with the syntax <& component_name, [variables] &>; this particular component is defined in a <%def>...</%def> section. Note the use of a leading % to denote a single line of Perl code.
  • We next set up a loop to print out all available environment variables. As well as the .bgcolor component used previously, this block uses the .font component. This particular component also uses a <%perl>...</%perl> section to handle passing of arguments from the <& component_name, [variables] &> call.
  • Finally, we use a <%once>...</%once> section to set the variables used in determining the background color for the table row.

If we look carefully at the screenshot we will notice that the page has a title and a line, which we didn't set explicitly. What happened is that we have also defined a special component file called autohandler, which gets called every time a top-level component is invoked and which is interpreted before the called components are interpreted. The component used in this particular example, which should also be placed in the directory specified by the /mason location in httpd.conf, is listed below:

<HTML>    
<HEAD> <TITLE>Embedding Perl into Web Pages with HTML::Mason</TITLE>    
</HEAD>    
<BODY BGCOLOR="#FFFFFF">    
<B>Mason Example:</B>    
<% $m->call_next %>    
</BODY>    
</HTML>

The <% $m->call_next %> line passes control to the next component (in this case, the original page called). These handlers are directory based, meaning that it is very easy to change the layout of a large number of pages just by changing this particular component.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links