I've run into this problem with other 3rd-party object methods that
return lists instead of arrayrefs; when there's more than one item, TT
collapses them into an arrayref, which is great. But if there's only one
item, you just get that item by itself, not in a list. Obviously
XML::Simple has a nice option for dealing with this issue, but many
others don't. I solved this problem generically by adding a custom
function to my variable hash before processing:

        my %vars = (foo => SomeObject->new());
        $vars{'as_list'} = sub { return ref($_[0]) eq 'ARRAY' ? shift :
[ shift ] };
        $tt->process($file, \%vars);

Then anything that I expect to be a list gets run through this function
before I use it:

        [% should_be_a_list = foo.get_some_list() %]
        [% FOREACH item IN as_list(should_be_a_list) %]
                do stuff...
        [% END %]

I had initially conceived this as a virtual method, but vmethods only
work on unblessed refs, so if your list contains blessed objects, you're
out of luck. This way is a bit clunky, but it get's the job done. I
suppose one could build this into a plugin that adds the function to the
stash...

Jason

Uwe Voelker wrote:
> > is there a way in Template Toolkit to work around this, or should i
> > modify the $doc itself to solve the problem
> 
> The problem is not TT, but XML-Simple.
> 
> >>>>>my $doc = $xs->XMLin($file);
> 
> You need:
> XMLin($file, {ForceArray => [qw(GlobalConfiguration Group)]});

_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to