in reply to Re: Template Toolkit and Dynamic Database Lookups
in thread Template Toolkit and Dynamic Database Lookups

I was just looking at that yesterday. There doesn't seem to be a way of doing the following without querying the database twice:

if no records match (content) else foreach record (content) end end

It seems like something people would commonly need.

I was thinking of making an alternate version of Template::Plugin::DBI::Iterator where the content of get_first has been moved into new and where get_first is a dummy. One could then do the following:

[% RAWPERL %] local $Template::Plugin::DBI::ITERATOR = 'Template::Plugin::DBI::IteratorZ'; [% END %] ... [% SET query = DBI.query( 'SELECT rows FROM table' ) %] [% IF query.last %] content [% ELSE %] [% FOREACH item = query %] content [% END %] [% END %] ... [%# Still works the old way %] [% FOREACH item = DBI.query( 'SELECT rows FROM table' ) %] content [% END %]

(Untested)

Is there a better way? Or any other way?

Update: Added "without querying the database twice" and the "still works the old way" bit.

Replies are listed 'Best First'.
Re^3: Template Toolkit and Dynamic Database Lookups
by rinceWind (Monsignor) on Jan 06, 2006 at 16:19 UTC

    You could always run a SELECT COUNT(*) FROM table... first, to find out whether you have any content.

    --

    Oh Lord, won’t you burn me a Knoppix CD ?
    My friends all rate Windows, I must disagree.
    Your powers of persuasion will set them all free,
    So oh Lord, won’t you burn me a Knoppix CD ?
    (Missquoting Janis Joplin)