开发者

Template toolkit IF on an empty array ref returns true, can I make it false?

开发者 https://www.devze.com 2023-02-08 10:37 出处:网络
So it seems that if I give template toolkit a reference to an array as a parameter ARRAY_REF => \\@array

So it seems that if I give template toolkit a reference to an array as a parameter

ARRAY_REF => \@array

and then have the following code in a template

[% IF ( AR开发者_开发知识库RAY_REF ) %]
  Do something
[% ELSE %]
  Do something else
[% END %]

The else case never gets triggered.

Replacing the parameter code with

ARRAY_REF => @array ? \@array : undef;

seems to solve the issue, however I was wondering if there is a way to make template toolkit evaluate an empty array (passed via reference) as false as there are many instances throughout my project where I believe this is being used (as in HTML template pro it worked as expected).

Thank you all in advance for your assistance.


Your ARRAY_REF will be true because it is defined and it would be a true value in Perl. The usual approach is to check that it is true and non-empty:

[% IF ARRAY_REF && ARRAY_REF.size %]
    Do something
[% ELSE %]
    Do something else
[% END %]

Say what you really mean, asking the computer to pretend to be smarter than it is leads to odd surprises.

You could probably change TT's notion of truthiness but I don't think you'd enjoy it or the various unpleasant side effects you'd probably come across. Template Toolkit isn't HTML Template Pro, when in Rome do as the Romans do and all that.

Your best bet is to fix your templates and consider the extra work as just part of the porting process. You could probably build a plugin to do the "true and non-empty" stuff for you though.


I think .size is what you want.

perl -MTemplate -le '$t = Template->new; $t->process(\"[% \"O HAI\" IF arrayref.size %]", { arrayref => [] })'

perl -MTemplate -le '$t = Template->new; $t->process(\"[% \"O HAI\" IF arrayref.size %]", { arrayref => [1] })'
O HAI

I'd also offer that an empty array ref is true in plain Perl–

perl -le '$abc = []; print "true" if $abc'
true

And when you do it directly it's more obvious (maybe) why it should be obvious–

perl -le 'print "true" if []'
true


Test by accessing the 1st array element:

[% IF ( ARRAY_REF.0 ) %]
0

精彩评论

暂无评论...
验证码 换一张
取 消