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

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

ARRAY_REF => \@array 

and then the following code in the template

 [% IF ( ARRAY_REF ) %] Do something [% ELSE %] Do something else [% END %] 

The else case never fires.

Replacing the parameter code

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

seems to solve the problem, however, I was wondering if there is a way to make the template toolkit for calculating an empty array (passed through a link) false, because there are a lot of instances in my project, where I believe that this is used (as the pro HTML template worked, as was expected).

Thank you in advance for your help.

+6
perl template-toolkit
source share
3 answers

Your ARRAY_REF will be true because it is defined and will be a true value in Perl. The usual approach is to verify 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 by asking the computer to pretend to be smarter than this leads to unexpected surprises.

Perhaps you could change TT's concept of truthfulness , but I donโ€™t think you will like this or the various unpleasant side effects that you are likely to encounter. The Template Toolkit is not an HTML Pro template when in Rome they do what the Romans do and all that.

Itโ€™s best to fix your templates and consider additional work as part of the porting process. Perhaps you could create a plugin to do the โ€œtrue and non-emptyโ€ things for you.

+22
source share

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 also suggest that the empty ref array be true in regular Perl -

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

And when you do it directly, it is more obvious (maybe) why it should be obvious -

 perl -le 'print "true" if []' true 
+10
source share

Check access to the element of the 1st array:

 [% IF ( ARRAY_REF.0 ) %] 
-3
source share

All Articles