将对象传递到Template::Toolkit

3
我正在编写一个脚本,将我的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->items())并打印每个日志的标题。当我运行这段代码时,会得到以下输出:

var.undef error - undefined variable: items

为了使其工作,我不得不将process行更改为:

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

请问为什么Template::Toolkit似乎不能使用XML::Feed->items()方法?

我之前使用过XML::RSS,感觉类似:

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

3

只需要进行一些微调。

#!/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 }

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


@RobEarl,模板编译器需要一个哈希引用,其中包含指向$feed对象的键。从那里开始,它就可以轻松调用items方法。 - ddoxey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接