in reply to Template Toolkit and Dynamic Database Lookups

Check out Template::Plugin::DBI that comes with the Template Toolkit distribution.

--

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)

  • Comment on Re: Template Toolkit and Dynamic Database Lookups

Replies are listed 'Best First'.
Re^2: Template Toolkit and Dynamic Database Lookups
by ikegami (Patriarch) on Jan 06, 2006 at 15:59 UTC

    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.

      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)