⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch06_03.htm

📁 用perl编写CGI的好书。本书从解释CGI和底层HTTP协议如何工作开始
💻 HTM
📖 第 1 页 / 共 2 页
字号:
    { name     =&gt; "Martha",      location =&gt; "Orlando",      age      =&gt; "51" },    { name     =&gt; "Betty",      location =&gt; "Los Angeles",      age      =&gt; "19" },    ...);</pre></blockquote></div><p><a href="ch06_03.htm#ch06-70025">Example 6-6</a> contains a script that will display allof the standard colors available on systems that support the X Windowsystem.</p><a name="ch06-70025" /><div class="example"><h4 class="objtitle">Example 6-6. xcolors.cgi</h4><blockquote><pre class="code">#!/usr/bin/perl -wTuse strict;use HTML::Template;my $rgb_file = "/usr/X11/lib/X11/rgb.txt";my $template = "/usr/local/apache/templates/xcolors.tmpl";my @colors   = parse_colors( $rgb_file );print "Content-type: text/html\n\n";my $tmpl = new HTML::Template( filename =&gt; $template );$tmpl-&gt;param( colors =&gt; \@colors );print $tmpl-&gt;output;sub parse_colors {    my $path = shift;    local *RGB_FILE;    open RGB_FILE, $path or die "Cannot open $path: $!";        while (&lt;RGB_FILE&gt;) {        next if /^!/;        chomp;        my( $r, $g, $b, $name ) = split;                # Convert to hexadecimal #RRGGBB format        my $rgb = sprintf "#%0.2x%0.2x%0.2x", $r, $g, $b;                my %color = ( rgb =&gt; $rgb, name =&gt; $name );        push @colors, \%color;    }        close RGB_FILE;    return @colors;}</pre></blockquote></div><p>This CGI script uses the <tt class="function">rgb.txt</tt> file that istypically found on X Window systems at<em class="filename">/usr/X11/lib/X11/rgb.txt</em>. This file contains alist of colors along with their 8-bit values for red, green, andblue:</p><blockquote><pre class="code">! $XConsortium: rgb.txt,v 10.41 94/02/20 18:39:36 rws Exp $255 250 250	    snow248 248 255	    ghost white248 248 255	    GhostWhite245 245 245	    white smoke245 245 245	    WhiteSmoke...</pre></blockquote><p>We read the red, green, and blue values and convert them to thehexadecimal equivalent that is used on HTML pages (e.g.,<tt class="literal">#336699</tt>). We create a separate hash for each colorwith an entry for the RGB value and the name of the color. Then weadd each hash to the array <tt class="literal">@colors</tt>. We need topass only <tt class="literal">@colors</tt> as a parameter toHTML::Template, which we can use as a loop variable within our HTMLtemplate. Within the loop, we have access to the "rgb"and "name" elements of our hashes, as shown in <a href="ch06_03.htm#ch06-70010">Example 6-7</a>.</p><a name="ch06-70010" /><div class="example"><h4 class="objtitle">Example 6-7. xcolors.tmpl</h4><blockquote><pre class="code">&lt;HTML&gt;&lt;HEAD&gt;  &lt;TITLE&gt;X11 Color Viewer&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY BGCOLOR="white"&gt;&lt;DIV ALIGN="center"&gt;  &lt;H1&gt;X11 Color Viewer&lt;/H1&gt;  &lt;HR&gt;    &lt;TABLE BORDER="1" CELLPADDING="4" WIDTH="400"&gt;    &lt;TMPL_LOOP NAME="colors"&gt;      &lt;TR&gt;        &lt;TD BGCOLOR="&lt;TMPL_VAR NAME="rgb"&gt;"&gt;          &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/TD&gt;        &lt;TD&gt;&lt;TMPL_VAR NAME="name"&gt;&lt;/TD&gt;      &lt;/TR&gt;    &lt;/TMPL_LOOP&gt;  &lt;/TABLE&gt;&lt;/DIV&gt;&lt;/BODY&gt;&lt;/HTML&gt;</pre></blockquote></div><p>This loop structure is flexible enough to allow us to display otherforms of data, such as hashes. <a href="ch06_03.htm#ch06-58970">Example 6-8</a> lists aCGI script that generates all of the environment variables and theirvalues.</p><a name="ch06-58970" /><div class="example"><h4 class="objtitle">Example 6-8. env_tmpl.cgi </h4><a name="INDEX-1378" /><a name="INDEX-1,379" /><blockquote><pre class="code">#!/usr/bin/perl -wTuse strict;use HTML::Template;use constant TMPL_FILE =&gt; "$ENV{DOCUMENT_ROOT}/templates/env.tmpl";my $tmpl = new HTML::Template( filename =&gt; TMPL_FILE,                               no_includes =&gt; 1 );my @env;foreach ( sort keys %ENV ) {    push @env, { var_name =&gt; $_, var_value =&gt; $ENV{$_} };}$tmpl-&gt;param( env =&gt; \@env );print "Content-type: text/html\n\n",      $tmpl-&gt;output;</pre></blockquote></div><p>HTML::Template has no facility for handling<a name="INDEX-1380" />hashes directly, but because it will loopover <a name="INDEX-1381" />arrays ofhashes, we build a hash for each pair in <tt class="literal">%ENV</tt> andadd it to an array, <tt class="literal">@env</tt>. We then pass a referenceto <tt class="literal">@env</tt> as a parameter to our HTML::Templateobject and output the parsed file. Our template file is shown in<a href="ch06_03.htm#ch06-54470">Example 6-9</a>.</p><a name="ch06-54470" /><div class="example"><h4 class="objtitle">Example 6-9. env.tmpl </h4><a name="INDEX-1382" /><a name="INDEX-1,383" /><blockquote><pre class="code">&lt;HTML&gt;&lt;HEAD&gt;  &lt;TITLE&gt;Environment Variables&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY BGCOLOR="white"&gt;  &lt;TABLE BORDER="1"&gt;    &lt;TMPL_LOOP NAME="env"&gt;      &lt;TR&gt;        &lt;TD&gt;&lt;B&gt;&lt;TMPL_VAR NAME="var_name"&gt;&lt;/B&gt;&lt;/TD&gt;        &lt;TD&gt;&lt;TMPL_VAR NAME="var_value"&gt;&lt;/TD&gt;      &lt;/TR&gt;    &lt;/TMPL_LOOP&gt;  &lt;/TABLE&gt;&lt;/BODY&gt;&lt;/HTML&gt;</pre></blockquote></div><p>Note that we called <tt class="function">param</tt> once, even thoughthere are three different HTML::Template tags in this file. The<tt class="literal">var_name</tt> and <tt class="literal">var_value</tt>variables were set because they corresponded to hash keys within the<tt class="literal">@env</tt> array.</p></div><a name="ch06-7-fm2xml" /><div class="sect3"><h3 class="sect3">6.3.1.2. Conditionals</h3><p><a name="INDEX-1384" /> <a name="INDEX-1,385" />HTML::Templateoffers two ways to create a conditional just like Perl: TMPL_IF andTMPL_UNLESS. You can use these to include or omit particular portionsof your HTML template. Both tags take a <a name="INDEX-1386" /><a name="INDEX-1387" />NAMEattribute that corresponds to a parameter, just like previous tags,which is evaluated in a boolean context. There is no way to createexpressions to evaluate within your templates, since the goal is tokeep templates simple. Note also that you do not always have to set aseparate parameter in order to use these tags. For example, you couldinclude a block like this in your document:</p><blockquote><pre class="code">&lt;TMPL_IF NAME="secret_msg" &gt;  &lt;P&gt;Psst, here's your secret message: &lt;TMPL_VAR NAME="secret_msg"&gt;.&lt;/P&gt;&lt;/TMPL_IF&gt;</pre></blockquote><p>Here the same parameter is used in both the TMPL_IF and TMPL_VARcommands. If there is a secret message, it is displayed. If thereisn't (i.e., if it is an empty string), then nothing isdisplayed instead.</p><p>You can also use<a name="INDEX-1388" /><a name="INDEX-1389" />loop parameters as conditions. Ifthe loop parameter contains any values, it returns true; otherwise itreturns false. This is useful for displaying search results whenthere are no matches:</p><blockquote><pre class="code">&lt;P&gt;Here are the results of your query:&lt;/P&gt;&lt;TABLE&gt;  &lt;TR&gt;    &lt;TH&gt;Software Title&lt;/TH&gt;&lt;/TR&gt;    &lt;TH&gt;Home Page&lt;/TH&gt;&lt;/TR&gt;  &lt;/TR&gt;  &lt;TMPL_LOOP NAME="results"&gt;  &lt;TR&gt;    &lt;TD&gt;&lt;TMPL_VAR NAME="sw_title"&gt;&lt;/TD&gt;    &lt;TD&gt;&lt;A HREF="&lt;TMPL_VAR NAME="url"&gt;"&gt;&lt;TMPL_VAR NAME="sw_url"&gt;&lt;/A&gt;&lt;/TD&gt;  &lt;/TR&gt; &lt;/TMPL_LOOP&gt;  &lt;TMPL_UNLESS NAME="results"&gt;  &lt;TR&gt;    &lt;TD COLSPAN="2"&gt;      No software titles match your query.    &lt;/TD&gt;  &lt;/TR&gt; &lt;/TMPL_UNLESS&gt;&lt;/TABLE&gt;</pre></blockquote><p>In this example, a user is searching for software according to somecriteria. If the query matches any titles, then the name and homepage of the titles are displayed on separate rows in a table. If norows match, then the script says this instead. This template givesthe interface designer full control over how the results arepresented to the user without being too complicated to understand.</p></div><a name="ch06-8-fm2xml" /><div class="sect3"><h3 class="sect3">6.3.1.3. Including other files</h3><p>The final command,<a name="INDEX-1390" />TMPL_INCLUDE, includesthe content of other files in your template. The content of thesefiles is included before loops and variables are parsed, so you caninclude files that contain loop and variable tags (or even otherinclude tags). This is similar to the SSI<tt class="command">include</tt><a name="INDEX-1391" /> command, except there is no ability toprovide a virtual<a name="INDEX-1392" />path to thefile; you must provide a filesystem path. HTML::Template does novalidation that the file is within the document root, so an HTMLdeveloper could easily include the following statement in a file andHTML::Template would act accordingly:</p><blockquote><pre class="code">&lt;TMPL_INCLUDE NAME="/etc/passwd" &gt;</pre></blockquote><p>This is not as serious a security issue as it might appear, since anHTML designer could always copy the contents of<em class="emphasis">/etc/passwd</em> into an HTML file manually or createa symbolic link to it. However, this potential is something youshould be aware of. You can disable includes entirely with the<tt class="literal">no_includes</tt> option when you create anHTML::Template object.</p></div></div><a name="ch06-9-fm2xml" /><div class="sect2"><h3 class="sect2">6.3.2. Summary</h3><p>HTML::Template is certainly a very elegant solution for projectswhere the roles of HTML designers and developers are clearlyseparated. HTML::Template has only been available a short while buthas matured quickly. It also offers more advanced features includingcaching output that we haven't discussed. The features wediscussed are accurate as of Version 1.7, but new features are stillbeing added, so check the documentation for more information. You canfind <a name="INDEX-1393" /> <a name="INDEX-1,394" />HTML::Template on CPAN; for thelatest information, including information on the mailing list andCVS, consult the online <a name="INDEX-1395" /> <a name="INDEX-1,396" /> <a name="INDEX-1,397" /> <a name="INDEX-1,398" />documentation.</p></div><hr align="left" width="515" /><div class="navbar"><table border="0" width="515"><tr><td width="172" valign="top" align="left"><a href="ch06_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td width="171" valign="top" align="center"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0" /></a></td><td width="172" valign="top" align="right"><a href="ch06_04.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr><tr><td width="172" valign="top" align="left">6.2. Server Side Includes</td><td width="171" valign="top" align="center"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0" /></a></td><td width="172" valign="top" align="right">6.4. Embperl</td></tr></table></div><hr align="left" width="515" /><img src="../gifs/navbar.gif" alt="Library Navigation Links" usemap="#library-map" border="0" /><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2001</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"><area href="../index.htm" coords="1,1,83,102" shape="rect" /><area href="../lnut/index.htm" coords="81,0,152,95" shape="rect" /><area href="../run/index.htm" coords="172,2,252,105" shape="rect" /><area href="../apache/index.htm" coords="238,2,334,95" shape="rect" /><area href="../sql/index.htm" coords="336,0,412,104" shape="rect" /><area href="../dbi/index.htm" coords="415,0,507,101" shape="rect" /><area href="../cgi/index.htm" coords="511,0,601,99" shape="rect" /></map></body></html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -