Wednesday, July 1, 2009

Template Toolkit + CGI::Ajax Sample

I would like to say at the beginning that this would be the first and most detail sample for people who wants to use TT and CGI::Ajax together. Because I googled for a long time and cannot find any workable example. So I know the pain and hope this can help someone who has the same pain as me.

This example will not solve every problem of TT and CGI::Ajax integration, only one aspect of it, the basic one, and it's not the best one I think.

Okay, let's directly go to a workable code, the default CGI:
#!/usr/bin/perl

use strict;
use warnings;

use lib qw/ . /;
use vars qw/ $vars /

use Mypackage::User;

use Mypackage::CGI;
use CGI::Ajax;

my $cgi = Mypackage::CGI->cgi; # here we wrap the template into my own CGI so that they can use together easily
my $template = Mypackage::CGI->template;

print $cgi->header;

$vars->{title} = "test ajax";
$template->process( "header.html.tmpl", $vars ) or throw( $template->error ); # just process a html template file
my $ajax = CGI::Ajax->new( 'get_reservation' => 'ajax.cgi');
$ajax->JSDEBUG(1);
$ajax->DEBUG(1);

print $ajax->build_html( $cgi ); # inject CGI::Ajax

$template->process( "b.html.tmpl", $vars ) or throw( $template->error ); # do anything else
$template->process( "footer.html.tmpl", $vars ) or throw( $template->error );


exit 0;
__END__


Here we request the external cgi to deal with the request:

#!/usr/bin/perl

use strict;
use warnings;

use lib qw/ . /;
use vars qw/ $vars /;

use Mypackage::User;


use Mypackage::CGI;
use CGI::Ajax;

my $cgi = Mypackage::CGI->cgi;
my $template = Mypackage::CGI->template;

print $cgi->header;
my @args = $cgi->param( 'args' );
my $team = $args[0]; # you can get more than one parameter from here
print &get_users_func($team);

sub get_users_func
{
my ( $team ) = @_;
my $users = new Mypackage::User();
my $teamusers = $users->get( $team);
$vars->{users} = $teamusers;# vars is the VARIABLES of TT, you can see we use the same way that passing variables in an ajax context
$template->process( "c.html.tmpl", $vars ) or throw( $template->error ); // c.html.tmpl shows a list a user in this team
return $vars->{content}; # we simply return the content of processed template, you can have other way to return the content, but this will be the simplest way I think
}

exit 0;

Here's the codes you need to add into your default html file (b.html.tmpl):
<input type="text" id="team" value="[% team %]">
<div id="users"></div>
<p><input type="button" name="submit" value="show all users" onclick="get_users(['team'],['users'])"/></p>