Perl - Template Alloy and Template toolkit array ref

我们两清 提交于 2019-12-24 01:36:10

问题


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;
  }

}

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 ] ];
}

In the index.tt:

[% FOR base = menus %]

 [% FOR parent = base %]

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

 [% END %]

[% END %]

If I remove the IF statement, I get this:

parent ARRAY(0x2539ad8)

I want to just get parent

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

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


回答1:


This line is wrong in multiple ways:

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

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.

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.

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 %]

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.



来源:https://stackoverflow.com/questions/51539514/perl-template-alloy-and-template-toolkit-array-ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!