Template2 icon indicating copy to clipboard operation
Template2 copied to clipboard

VMethod 'defined' useless with STRICT = 1

Open LouisStrous opened this issue 7 years ago • 2 comments

Calling the 'defined' VMethod on an undefined variable raises the "undefined variable" error if template runtime option STRICT is on, so that VMethod is not useful then. It would be more useful if the raising of the "undefined variable" error were suppressed when the 'defined' VMethod is being processed.

Reproduction code:

use warnings;
use strict;

use Template;

my $text = '[% IF foo.defined; "Yes!"; ELSE; "No."; END %]';
my $tt = Template->new({ STRICT => 1 });
$tt->process(\$text) or die $tt->error();

This yields

var.undef error - undefined variable: foo.defined

with Template Toolkit version 2.27. I expected to get No. instead.

A workaround is to use the DEFAULT directive to assign a value to each variable that has none.

LouisStrous avatar Feb 22 '18 13:02 LouisStrous

I just tried STRICT mode and I think it's pretty useless this way:-(

I'd love to have this design:

  • printing a variable that doesn't exist→exception
  • printing a variable that is undef→print empty string, issue a warning (updated)
  • checking a variable that's undef with IF or WHILE→condition is false
  • checking a variable that doesn't exist→exception
  • .defined on a variable that doesn't exist→exception
  • .defined on a variable that's undef→false
  • .exists on a variable that doesn't exist→false

Is this possible as a fix/setting/plugin?

dboehmer avatar Jan 18 '20 04:01 dboehmer

I'd love to have this design:

That'd be wonderful. We've had to avoid turning on STRICT because of no way to safely check for a NULL value being returned from a database field, which now means we aren't catching typos in variable names (or even in directives: [% ESLE %] was a fun one).

It would have to have a different name to STRICT, but that isn't a problem.

Smylers avatar Dec 31 '21 08:12 Smylers