Template Toolkit and lazy Moose attributes - how to make them behave?

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

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

then in the Template :: Toolkit template I will try to use this attribute:

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

I won’t get anything. I have to call this attr attribute in the perl script before processing the attribute with TT. Is there a way for TT to initialize this attr by itself?

+6
source share
1 answer

I assume that you are passing the Moose object this way.

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

The second parameter is considered a hehref, and not some blissful object (moose or not).

So, the Moose object is treated as a simple hash and has no β€œcolor” key until you populate it by calling Accessor outside the 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 the way you expect.

+13
source

Source: https://habr.com/ru/post/918258/


All Articles