Heidegger has asked for the wisdom of the Perl Monks concerning the following question:

Holy Monks,

I'm trying to use the Template::Toolkit module for a CGI application. Here's the code I use:

my $output = "Content-type: text/html\n\n"; my $file = 'index.html'; my $vars = { title => "Hello World\n" }; my $template = Template->new({ INCLUDE_PATH => 'C:/Apache2/htdocs/gelna/templates' } ); $output .= $template->process($file, $vars) || die "Template process + failed: ", $template->error(), "\n"; print $output;

The ouput from this code is this:

C:\Apache2\htdocs\gelna>perl index.cgi <HTML> <head> <title>This is an HTML example</title> </head> <body bgcolor="#ffffff"> <h1></h1> <hr> <center> &copy; Copyright 2000 Me, Myself, I </center> </body> </html> Content-type: text/html 1

Thus, the HTML header goes after the template output. I can't make it go first. What am I doing wrong here? BTW, in the beginning I tried to use the CGI::Application together with it. And I also couldn't make the header go before the template processing output. The Template::Toolkit seems to process my template well. It's just the header that doesn't work. And the "1" value at the end of the output bothers me too.

Thank you.

Replies are listed 'Best First'.
Re: Template::Toolkit + CGI header
by edoc (Chaplain) on Jun 02, 2003 at 07:09 UTC

    yup, Template Toolkit prints the template to STDOUT by default.

    replace: $output .= $template->process($file, $vars) || with: $template->process($file, $vars, \$output) ||

    and it should append the template to $output.

    or..

    replace: my $output = "Content-type: text/html\n\n"; with: print "Content-type: text/html\n\n";

    and get rid of the print $output statement at the end.

    I prefer the first option as you can then pass the content to other subs, back to the caller, print it to a file, or anything else you may want to do with it..

    cheers,

    J

Re: Template::Toolkit + CGI header
by tedrek (Pilgrim) on Jun 02, 2003 at 06:50 UTC
    I'm not familiar with Template::Toolkit but my guess is you'll find $template->process(... prints the template for you and returns 1 on success. So when you go to print $ouput the template has already been printed.
      I see. But then how to print the HTML header then? There must be a way to tell the Template::Toolkit to print the HTML header, but how to do that?

        Others have pointed out the solutions where you can either print the header before processing the template, or use the third argument to process to append the template output to the end of $output. But no-one has yet suggested perhaps the simplest solution - add the header to your template.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg