How to detect array type in Template toolkit? [closed]

寵の児 提交于 2019-12-11 01:55:17

问题


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

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