我使用模板合金和模板工具包,在 TT 中我想像使用 perl 一样检测数组引用:
for my $parents ( @{$value} ){
if (ref($parents) ne 'ARRAY'){
push @all_urls_names, $parents;
}
}
这是我在 tt 中的代码:
use warnings;
use v5.20; #strict is already set in the version
use Template;
my $t = Template->new(
INCLUDE_PATH => ['.'],
);
my @menus = (
["parent",
[qw(child1 child12 child13 child14) ]
],
);
my $mvs = {# my variables
menus => \@menus
};
$t->process("index.tt", $mvs, \my $out) || die $t->error;
sub {
return [ 200, [], [ $out ] ];
}
在index.tt中:
[% FOR base = menus %]
[% FOR parent = base %]
[% IF ref.parent ne "ARRAY" %]
<li>[% parent %] </li>
[% END %]
[% END %]
[% END %]
如果我删除 IF
语句,我会得到:
parent 阵列(0x2539ad8)
我只想获取parent
我可以修复 [% FOR parent = base.0 %]
但我想知道在 TT 中获取 ref 数组的解决方案。
最佳答案
这一行在很多方面都是错误的:
[% IF ref.parent ne "ARRAY" %]
您尝试取消引用一个(不存在的)变量 ref
。相反,您需要像 parent.ref()
这样的东西来调用变量 parent
上的 VMethod ref
。但是Template Toolkit中没有这样的VMethod。
Template Toolkit 中也没有操作符ne
。它是 !=
。您必须找出记录语法错误的位置并进行检查。
虽然有一个 hack 可以查明一个变量是否是一个普通的数组引用。您可以使用您的示例 Perl 文件尝试此代码:
[% stringified = '' _ menus %]
[% IF stringified.match('ARRAY\\(0x[0-9a-f]+\\)') %]
array ref ([% stringified %])
[% ELSE %]
not an array ref ([% stringified %])
[% END %]
基本上,这会检查变量 menus
在强制转换为字符串时是否与 Template Toolkit(和 Perl)中数组引用的默认呈现相匹配。这是一个有很多注意事项的 hack,但是当您知道您的输入数据时,它可以用于实际目的。
关于Perl - 模板合金和模板工具包数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539514/