如何在模板工具包中检测数组类型?

bib*_*mij 3 perl types template-toolkit

我需要在模板工具包中检测数组类型附件的一些变量。有最佳实践吗?

Chr*_*ris 5

可以定义一个自定义虚拟方法,该方法返回所提供变量的 ref 类型。粗略的例子:

#!/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 %]
Run Code Online (Sandbox Code Playgroud)

输出:

ref type of 1 is 
ref type of ARRAY(0x9cfbd0) is ARRAY
ref type of HASH(0x9cfc00) is HASH
Run Code Online (Sandbox Code Playgroud)

  • 感谢分享这个,克里斯。我仍然坚持我最初的断言,即 OP 的问题可能是他以超出最佳实践的方式使用模板的症状。一个人的数据格式不应该是一个需要检查 ref 类型的级别的谜,如果它是控制器或模型中的缺陷。不过,感谢您分享此高级功能。+1 (3认同)