问题
I need to detect some variable for accessory to array type in Template toolkit. Are there best practices?
回答1:
Your data should be validated by the controller BEFORE it's passed to the template. There should be no mystery what format your data is in.
That said, the most useful method to check this would just be testing the array's size:
[% IF var.size %]
[% END %]
回答2:
It would be possible to define a custom virtual method which returns the ref type of the variable supplied. Rough example:
#!/usr/bin/perl
use strict;
use warnings;
use Template;
use Template::Stash;
$Template::Stash::SCALAR_OPS->{ ttref } = \&ttref;
$Template::Stash::LIST_OPS ->{ ttref } = \&ttref;
$Template::Stash::HASH_OPS ->{ ttref } = \&ttref;
my $t = Template->new( );
$t->process( \*DATA, { vars => [ 1, [ ], { } ] } );
sub ttref
{
return ref $_[0];
}
__DATA__
[% FOREACH var IN vars -%]
ref type of [% var %] is [% var.ttref %]
[% END %]
Output:
ref type of 1 is
ref type of ARRAY(0x9cfbd0) is ARRAY
ref type of HASH(0x9cfc00) is HASH
来源:https://stackoverflow.com/questions/23912898/how-to-detect-array-type-in-template-toolkit