How to detect array type in Template toolkit? [clo

2019-07-20 19:52发布

I need to detect some variable for accessory to array type in Template toolkit. Are there best practices?

2条回答
萌系小妹纸
2楼-- · 2019-07-20 20:45

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 %]
查看更多
Emotional °昔
3楼-- · 2019-07-20 20:48

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
查看更多
登录 后发表回答