abw / Template2

Perl Template Toolkit v2
http://template-toolkit.org/
146 stars 94 forks source link

Can't iterate on CONSTANTS #207

Open assistcontrol opened 5 years ago

assistcontrol commented 5 years ago

I am having trouble iterating on CONSTANTS.

If I pass in: CONSTANTS: { foo => [1, 2, 3] }

Then:

  [% constants.foo.size %]
  [% FOREACH constants.foo %]
    Hello
  [% END %]

Should print:

  3 Hello Hello Hello

Instead, it just prints: 3

Interestingly, [% foo.first %] works. I'm seeing the same problem iterating hashrefs.

What am I missing about CONSTANTS behaviour?

gflohr commented 5 years ago

This looks like a syntax error. Try [% FOREACH item IN constants.foo %].

You probably get a quicker answer to this type of question on stackoverflow: https://stackoverflow.com/questions/tagged/template-toolkit

assistcontrol commented 5 years ago

That doesn't work either.

[% constants.foo.size %]
[% FOREACH item IN constants.foo %]
  Hello
[% END %]

Output: 3

gflohr commented 5 years ago

[% FOREACH item IN constants.foo %] Hello [% END %]

Then your Perl code that invokes the template processor has a bug. Please post it here. You are doing something like:

$constants->{foo} = @items;

When you should do:

$constants->{foo} = [@items];

If that doesn't help, please post your complete code or a reference to it.

This here works, by the way:

[% constants.foo = ['foo', 'bar', 'baz'] %]
[% FOREACH item IN constants.foo %]
  Hello
[% END %]
assistcontrol commented 5 years ago

I appreciate all your help here, @gflohr!

This is what I'm using:

use Template;

my $T = Template->new({
    CONSTANTS => { foo => [1, 2, 3] }
});

$T->process(\*DATA, { alist => [4, 5, 6] });

__END__
Constant:

  Size: [% constants.foo.size %]
  Bare: [% FOREACH constants.foo %] Hello [% END %]
  Iter: [% FOR item IN constants.foo %] Hello [% END %]

Var:

  Size: [% alist.size %]
  Bare: [% FOREACH alist %] Hello [% END %]
  Iter: [% FOR item IN alist %] Hello [% END %]
gflohr commented 5 years ago

Sorry, I didn't even know about the options CONSTANTS and CONSTANTS_NAMESPACE. I can try to have a look but I'm afraid that won't happen before Monday.

assistcontrol commented 4 years ago

Any thoughts on this? This seems like a bug.