[Templates] Databased Templates

Paul Seamons mail at seamons.com
Wed Jan 30 20:34:13 GMT 2008


> Sorry if this has been covered before (if so can someone point me to the
> relevant archive? TIA), but can anyone help me get started setting up
> getting TT templates out of a database?

I know there are other modules that will let you do something similar, but 
personally I like using the following undocumented mechanism:

perl -e 'use Template;
  sub lookup_template { return \"Custom template (@_)\n"}
  my $t=Template->new;
  $t->process(\q{Process [% temp = my_db_template("foo"); PROCESS $temp %]},
              {
                my_db_template => \&lookup_template,
              }) || die $t->error'

The undocumented feature is that PROCESS will use the value of $temp to lookup 
the template, and if the template contains a reference to a string, it will 
process it just fine.  To make this work with a db, you insert your own 
custom lookup code into the my_db_template sub. 

The downside is that this avoids caching at the moment in TT - and TT requires 
you to use a temporary variable to pass to PROCESS.  If however you 
replace "Template" above with "Template::Alloy", then even your string refs 
get caching and you can interpolate the function directly.

perl -e 'use Template::Alloy;
  sub lookup_template { return \"Custom template (@_)\n"}
  my $t=Template::Alloy->new;
  $t->process(\q{Process [% PROCESS ${ my_db_template("foo") } %]},
              {
                my_db_template => \&lookup_template,
              }) || die $t->error'

This is the simplest and most extensible solution - but the syntax may be more 
ugly than you want.  If you want "normal" looking "filenames" to translate 
into db calls, you'll need an overridden Template::Provider solution.

Paul



More information about the templates mailing list