Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ( ARRAY_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.

like image 801
cjh Avatar asked Feb 03 '11 03:02

cjh


2 Answers

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.

like image 81
mu is too short Avatar answered Oct 18 '22 08:10

mu is too short


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
like image 11
Ashley Avatar answered Oct 18 '22 08:10

Ashley