如何使用CGI.pm向popup_menu添加自定义属性?

时间:2014-11-05 18:15:25

标签: perl cgi

我使用以下Perl代码生成带有CGI.pm的HTML弹出菜单:

$html->popup_menu(
    -name     => "to",
    -values   => [@TO, $param_to],
    -labels   => {%TO, $param_to => $param_to,},
    -default  => $param_to,
    -onchange => $onchange,
    -class    => "form-control"
);

生成的菜单如下所示:

<select name="to" onchange="if (this.value=='support@abc.com' || document.theForm.supportform.value==1) document.theForm.submit();" class="form-control">
<option value=""> select recipient </option>
<option value="sales@abc.com">Sales Inquiry</option>
<option value="support@abc.com">Technical Support</option>
<option value="jobs@abc.com">Jobs @ abc</option>
<option value="investor-relations@abc.com">Investor Relations</option>
<option value="webmaster@abc.com">abc Webmaster</option>
</select>

如何将属性required添加到<select>元素?

1 个答案:

答案 0 :(得分:1)

根据CGI文档:

  

许多例程将使用它无法识别的命名参数做一些有用的事情。

所以只需添加另一个命名参数-required

$html->popup_menu(
    -name     => "to",
    -values   => [@TO, $param_to],
    -labels   => {%TO, $param_to => $param_to,},
    -default  => $param_to,
    -onchange => $onchange,
    -class    => "form-control",
    -required => "required"
);

这将生成如下内容:

<select name="to" ... required="required">

然而,使用CGI.pm生成HTML是一种痛苦,而且难以维护。使用像Template Toolkit这样的模板库会更好。模板允许您分离Perl代码和HTML(主要是),因此您可以使用以下内容:

popup.tt

<select name="to" onchange="if (this.value=='support@abc.com' || document.theForm.supportform.value==1) document.theForm.submit();" class="form-control">
  [% FOR option IN options %]
  <option value="[% option.value %]">[% option.text %]</option>
  [% END %]
</select>

my_script.cgi

use strict;
use warnings;

use CGI;
use Template;

my $tt = Template->new or die Template->error;

my $q = CGI->new;
print $q->header;

my $options = [
    { value => '', text => 'select recipient' },
    { value => 'sales@abc.com', text => 'Sales Inquiry' },
    { value => 'support@abc.com', text => 'Technical Support' },
    { value => 'jobs@abc.com', text => 'Jobs @ abc' },
    { value => 'investor-relations@abc.com', text => 'Investor Relations' },
    { value => 'webmaster@abc.com', text => 'abc Webmaster' }
];

$tt->process('foo.tt', { options => $options }) or die $tt->error;

输出

<select name="to" onchange="if (this.value=='support@abc.com' || document.theForm.supportform.value==1) document.theForm.submit();" class="form-control">

  <option value="">select recipient</option>

  <option value="sales@abc.com">Sales Inquiry</option>

  <option value="support@abc.com">Technical Support</option>

  <option value="jobs@abc.com">Jobs @ abc</option>

  <option value="investor-relations@abc.com">Investor Relations</option>

  <option value="webmaster@abc.com">abc Webmaster</option>

</select>