6

If I declare lazy attribute in perl class using Moose, and the attribute is using builder:

has 'colors' => (
  is => 'rw',
  isa => 'ArrayRef',
  lazy => 1,
  builder => '_build_colors',
);

then in Template::Toolkit template I'll try to use this attribute:

[% FOREACH color IN colors %]
...
[% END %]

I'll get nothing. I have to call this attr manualy in perl script before processing the attribute with TT. Is there any way TT can initialize this attr by himself?

1 Answer 1

13

I am assuming you are passing the Moose object like this.

$template->process('some.tt', $moose_object, ... );

The second paramater is assumed to be a hashref, not any kind of blessed object ( Moose or not ).

So, the Moose object gets treated as a plain hash and does not have the 'colors' key until you populate it by calling the accessor outside Template Toolkit.

You need to do something like this:

$template->process('some.tt', { obj => $moose_object }, ... );

And then in your template:

[% FOREACH color IN obj.colors %]
...
[% END %]

Which should work as you expect it to.

3
  • 1
    Good guess of the OP's actual error! I bet you got bitten by this before :)
    – ikegami
    Jun 17, 2012 at 5:35
  • @ikegami Nope, but I have spent way too much time recently working with Template Toolkit and needing to study how the stash works.
    – Dre
    Jun 17, 2012 at 5:40
  • 1
    Yes, actual scheme was a little more complex, but in general your way worked for me, thanks!
    – Sly
    Jun 17, 2012 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.