Perl-模板合金和模板工具箱阵列参考 [英] Perl - Template Alloy and Template toolkit array ref

查看:99
本文介绍了Perl-模板合金和模板工具箱阵列参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用模板合金和模板工具包,在TT中,我想像使用perl一样检测数组引用:

I using template alloy and Template toolkit, in TT I want to detect array reference like i do with perl:

for my $parents ( @{$value} ){

  if (ref($parents) ne 'ARRAY'){
    push @all_urls_names, $parents;
  }

}

这是我在tt中的代码:

This is my code in 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中:

In the index.tt:

[% FOR base = menus %]

 [% FOR parent = base %]

   [% IF ref.parent ne "ARRAY" %]
      <li>[% parent %] </li>
   [% END %]

 [% END %]

[% END %]

如果删除IF语句,则会得到以下信息:

If I remove the IF statement, I get this:

父母 数组(0x2539ad8)

parent ARRAY(0x2539ad8)

我只想得到parent

我可以解决[%FOR parent = base.0%]

I can fix just doing [% FOR parent = base.0 %]

但是我想知道在TT中获取引用数组的解决方案.

but I want to know a solution to get ref array in TT.

推荐答案

此行在多种方面是错误的:

This line is wrong in multiple ways:

[% IF ref.parent ne "ARRAY" %]

您尝试取消引用(不存在)变量ref.相反,您希望使用类似parent.ref()的方法来对变量parent调用VMethod ref.但是Template Toolkit中没有这样的VMethod.

You try to dereference a (non-existing) variable ref. Instead you wanted something like parent.ref() to invoke a VMethod ref on the variable parent. But there is no such VMethod in Template Toolkit.

并且在模板工具包中也没有运算符ne. !=.您必须找出语法错误记录在何处并进行检查.

And there is also no operator ne in Template Toolkit. It's !=. You have to find out where syntax errors are logged and check that.

虽然可以找出变量是否为纯数组引用.您可以使用示例Perl文件尝试以下代码:

There is a hack though to find out whether a variable is a plain array reference. You can try this code with your example Perl file:

[% stringified = '' _ menus %]
[% IF stringified.match('ARRAY\\(0x[0-9a-f]+\\)') %]
    array ref ([% stringified %])
[% ELSE %]
    not an array ref ([% stringified %])
[% END %]

基本上,这将检查变量menus在被强制转换为字符串时是否与Template Toolkit(和Per​​l)中数组引用的默认呈现相匹配.这是一个有很多警告的技巧,但是当您知道输入数据时,它就可以用于实际目的.

Basically, this checks whether the variable menus, when coerced into a string, matches the default rendering of an array reference in Template Toolkit (and Perl). It's a hack with a number of caveats but it works for practical purposes, when you know your input data.

这篇关于Perl-模板合金和模板工具箱阵列参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆