Can I serve templates from a database?
Short answer: yes, Chris Nandor has done this for Slash. You need to
subclass Template::Provider. See the mailing list archives for further
info.
Can I fetch templates via http?
To do the job properly, you should sublcass Template::Provider to
Template::Provider::HTTP and use a PREFIX_MAP option to bind the
'http' template prefix to that particular provider (you may want to
go digging around in the Changes file around version 2.01 for
more info on PREFIX_MAP - it may not be properly documented anywhere
else...yet!). e.g. (untested due to lack of existing HTTP Provider
- patches welcome!).
use Template::Provider::HTTP;
my $file = Template::Provider( INCLUDE_PATH => [...] );
my $http = Template::Provider::HTTP->new(...);
my $tt2 = Template->new({
LOAD_TEMPLATES => [ $file, $http ],
PREFIX_MAP => {
file => '0', # file:foo.html
http => '1', # http:foo.html
default => '0', # foo.html => file:foo.html
}
});
Now a template specified as:
[% INCLUDE foo %]
will be served by the 'file' provider (the default). Otherwise you
can explicitly add a prefix:
[% INCLUDE file:foo.html %]
[% INCLUDE http:foo.html %]
[% INCLUDE http://www.xyz.com/tt2/header.tt2 %]
This same principal can be used to create a DBI template provider. e.g.
[% INCLUDE dbi:foo.html %]
But similarly, alas, we don't yet have a DBI provider as part of the
Template Toolkit. There has been some talk on the mailing list about
efforts to develop DBI and/or HTTP providers but as yet no-one has
stepped forward to take up the challenge...
In the mean time, Craig's post from the mailing list has some useful
pointers on how to acheive this using existing modules:
To: Adam Theo <adamtheo@theoretic.com>
From: Craig Barratt <craig@arraycomm.com>
Date: Fri, 18 May 2001 17:06:59 -0700
> i was wondering if there is anyway to fetch a file using http:// or
> ftp:// and include that?
Here's one way. Set the LOAD_PERL option:
use Template;
my $template = Template->new({
LOAD_PERL => 1
});
$template->process("example.tt", { stdout => *STDOUT })
|| die $template->error();
and then use LWP::UserAgent and HTTP::Request:
[%
USE ua = LWP.UserAgent;
ua.proxy("http", "http://your_proxy/");
USE req = HTTP.Request("GET", "http://www.cpan.org");
ua.request(req).content;
-%]
For FTP use Net::FTP:
[%
USE ftp = Net.FTP("ftp.cpan.org");
x = ftp.login("anonymous", "me@here.there");
x = ftp.cwd("/");
x = ftp.get("welcome.msg", stdout);
x = ftp.quit;
-%]
Normally ftp.get would write the file into the current directory.
Instead we pass stdout as a second argument so that it is written
to stdout. We set stdout to STDOUT in the variables we pass to
process.
Craig
Miscellaneous
|