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 ...

Get Perl Template Toolkit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.