[Catalyst] Template::Toolkit + Empty Lists
Matt S Trout
dbix-class at trout.me.uk
Tue Aug 1 16:11:36 CEST 2006
Mark Blythe wrote:
> This is slightly off-topic, but since I'm running into this problem
> while using Catalyst, I'm hoping that others on the list may have
> already solved it.
>
> I was writing a simple template today, using TT + DBIC. I had an
> object and was exercising a has_many relationship. I simply wanted to
> see if any rows had been returned. It seemed simple enough:
>
> [% SET children = parent.children %]
> [% IF children.list.size %]
> ...
> [% END %]
>
> Well, it turns out that the size will always be >= 1, because TT can't
> seem to handle an empty list. If the method called (parent.children)
> returns an empty list, TT will substitute the return value with an
> empty string: '''.
>
> I tried to think of a general idiom to check for a non-empty list
> being returned:
>
> [% IF children.defined %] # no, because the empty string is defined
> [% IF children %] # breaks if you return a single-element list with a
> zero: ( 0 )
> [% IF children != '' %] # breaks if you return a single-element list
> with an empty string: ( '' )
>
> Of those three, the last one seems to be the least-common valid use
> case, so I'm thinking I'll use that. It's painfully stupid looking,
> so I may hide it (actually, the reverse) in an "is_empty" vmethod.
>
> I know I can get around this specific DBIx use case by using a
> resultset instead. However, I just know this will bite me again under
> other circumstances, and I want to have a workable solution for
> dealing with empty lists under TT.
>
> Has anybody solved this reasonably well? Am I missing something basic?
Under DBIC 07+ you should find you have a children_rs method that returns a
resultset even when called in list context (as TT does for everything). Then
you could just call count on the rs ...
More information about the Catalyst
mailing list