O'Reilly logo

Perl Template Toolkit by David Cross, Andy Wardley, Darren Chamberlain

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Accessing Databases

In many ways, the integration of a templating system and a database is natural. From e-commerce sites to Microsoft Word’s MailMerge, database-backed template processing is very common. Indeed, this integration is one of the primary selling points of many systems, such as ASP and PHP.

You can integrate the Template Toolkit with a database in several ways. The most straightforward way is to simply use the DBI plugin. The DBI plugin is part of the standard Template Toolkit distribution, and provides a template-facing way to utilize Perl’s DBI module (see Programming the Perl DBI: Database Programming with Perl, by Alligator Descartes and Tim Bunce (O’Reilly), for details about the DBI).

In addition to DBI, several database-related modules are on CPAN, such as Class::DBI and DBIx::SearchBuilder, that can be used to abstract the database layer out of code. Using these modules from within the Template Toolkit is the same as using them in Perl programs.

Writing your own abstraction layer is always an option as well. Many people like to keep SQL out of application code, for the same reasons that people prefer to keep business logic out of presentation templates; this is the primary purpose of a database abstraction layer. Many SQL-related helper modules are on CPAN, such as SQL::Abstract, SQL::OrderBy, SQL::QueryBuilder::Simple, and SQL::AnchoredWildcards, that can be used to help provide a non-SQL interface to a database.

Using the DBI Plugin

The DBI plugin provides ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required