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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With