【问题标题】:Passing Objects into Template::Toolkit将对象传递到 Template::Toolkit
【发布时间】:2012-12-03 13:24:16
【问题描述】:

我正在编写一个脚本来将我的 Stackoverflow 活动提要拉入网页,它看起来像这样:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Feed;
use Template;

my $stackoverflow_id = 1691146;
my $stackoverflow_url = "http://stackoverflow.com/feeds/user/$stackoverflow_id";

my $template = <<'TEMPLATE';
[% FOREACH item = items %]
[% item.title %]
[% END %]
TEMPLATE

my $tt = Template->new( 'STRICT' => 1 )
  or die "Failed to load template: $Template::ERROR\n";

my $feed = XML::Feed->parse(URI->new($stackoverflow_url));

$tt->process( \$template, $feed )
  or die $tt->error();

模板应该迭代我的活动提要(来自XML::Feed-&gt;items())并打印每个的标题。当我运行这段代码时,我得到:

var.undef error - undefined variable: items

为了让它工作,我必须将process 行更改为:

$tt->process( \$template, { 'items' => [ $feed->items ] } )

谁能解释为什么Template::Toolkit 似乎无法使用XML::Feed-&gt;items() 方法?

我与XML::RSS 有过类似的工作:

my $rss = XML::RSS->new();
$rss->parse($feed);
$tt->process ( \$template, $rss )
    or die $tt->error();

【问题讨论】:

    标签: xml perl atom-feed template-toolkit


    【解决方案1】:

    只是一些调整。

    #!/usr/bin/perl -Tw
    
    use strict;
    use warnings;
    
    use XML::Feed;
    use Template;
    use Data::Dumper;
    
    my $stackoverflow_id = 1691146;
    my $stackoverflow_url = "http://stackoverflow.com/feeds/user/$stackoverflow_id";
    
    my $template = <<'TEMPLATE';
    [% FOREACH item = feed.items() %]
    [% item.title %]
    [% END %]
    TEMPLATE
    
    my $tt = Template->new( 'STRICT' => 1 )
      or die "Failed to load template: $Template::ERROR\n";
    
    my $feed = XML::Feed->parse(URI->new($stackoverflow_url));
    
    
    
    $tt->process( \$template, { feed => $feed } )
      or die $tt->error();
    

    模板编译器需要一个普通的哈希引用,其键和值都存储在内部。给它一个XML::RSS 对象,因为它有一个items 元素。 XML::Feed 对象没有items 元素,因为它只是几个实现的包装器(包括XML::RSS)。模板不会得到XML::Feed 对象,它会得到一个普通的哈希引用,类似于:

    { 'rss' => XML::RSS Object }
    

    将您的提要包装在哈希 ref 中会使编译器保留 XML::Feed 对象,从而允许处理引擎在模板中找到 feed.items 时执行所需的“魔法”。

    【讨论】:

    • @RobEarl,模板编译器需要一个哈希引用,其键指向 $feed 对象。从那里调用 items 方法没有问题。
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2012-02-08
    • 2012-03-12
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    相关资源
    最近更新 更多