Home arrow Perl Programming arrow Page 6 - Getting Started with the Perl Template Toolkit

The Template Module - Perl

This chapter compares the Template Toolkit to other templating systems such as HTML::Mason and HTML::Template, describes how to install it, then shows you what templates look like and how to process them. (From the book, Perl Template Toolkit, O'Reilly Media, ISBN: 0596004761, by Darren Chamberlain, Dave Cross and Andy Wardley.)

TABLE OF CONTENTS:
  1. Getting Started with the Perl Template Toolkit
  2. The Templating Ecosystem
  3. Installing the Template Toolkit
  4. Documentation and Support
  5. Using the Template Toolkit
  6. The Template Module
  7. The Template Toolkit Language
  8. Dynamic Variables
  9. Template Processing Directives
  10. Integrating and Extending the Template Toolkit
By: O'Reilly Media
Rating: starstarstarstarstar / 23
July 28, 2004

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Both tpage and ttree use the Template Perl module to do the dirty work of processing templates. As it happens, the Template module doesnít actually do much in the way of dirty work itself, but delegates it to other modules in the Template Toolkit with exotic names such as Template::Service, Template::Context, Template::Provider, and Template::Stash. The Template module provides a simple interface for using the Template Toolkit from Perl so that you donít have to worry about the complex underlying functionality that makes it work. Chapter 7 goes into greater detail about what lurks beneath the hood of the Template Toolkit, but for now we cover just the basics.

If you are already a Perl hacker experienced in using modules, the Template manpage gives you an executive summary to get you quickly up to speed. If youíre not a Perl hacker but would like to be, Learning Perl, Third Edition, by Randal Schwartz and Tom Phoenix (OíReilly) is a good place to start.

However, you donít need to know any Perl to use the Template Toolkit. Thanks to the tpage and ttree programs, you can build your entire web site or other template-based document system without ever having to write a line of Perl code. Nevertheless, itís useful to have a basic understanding of how the Template module is used in Perl programs (including tpage and ttree), even if you never plan on using the module. Also, certain features are accessible only through Perl (for example, the ability to define a subroutine to return the value for a variable), so there is a good chance that sooner or later you will want or need those Perl-specific features.

Example 1-6 shows a simple Perl program for processing the destruction.tt template from Example 1-1.

#!/usr/bin/perl

use strict;
use warnings;
use Template;

my $tt = Template->new();
my $input = 'destruction.tt';
my $vars = {
      planet => 'Earth', 
      captain => 'Prostetnic Vogon Jeltz',
      time => 'two of your earth minutes',
};

$tt->process($input, $vars)
     || die $tt->error();

Example 1-6. A Perl program for processing the Vogon form letter template

The first line defines the path to the Perl interpreter on your system. This is very much a Unix-specific convention. On a Windows machine, for example, this line is not relevant or required.

In the first block, we enable Perlís strict and warnings pragmata and then load the Template module:

use strict;
use warnings;
use Template;

It is good Perl style to include use strict; and use warnings; at the top of every program, or to invoke Perl with the -w switch instead of use warnings; for versions of Perl earlier than 5.6.0. These two precautions will catch many common programming and typographical errors, and warn you about any questionable practices. Perl examples in this book may omit them for brevity, but you should always include them in any nontrivial chunk of code.

The next line creates a new Template object and assigns it to the $tt variable:

my $tt = Template->new();

We store the name of the template to be processed in the $input variable and define some template variables in $vars:

my $input = 'destruction.tt2';
my $vars = {
      planet => 'Earth',
      captain => 'Prostetnic Vogon Jeltz',
      time => 'two of your earth minutes',
};

Then we invoke the process( ) method against the $tt template object to process the source template:

$tt->process($input, $vars)
     || die $tt->error();

The name of the source template file, here stored in the $input variable, is passed as the first argument, followed by a reference to a hash array of template variables, defined in $vars.

The process( ) method processes the template and returns a true value to indicate success. The output is printed to STDOUT by default so that you see it scrolling up your screen when you run the program.

If an error occurs, the process( ) method returns false. In this case, we call the error( ) method to find out what went wrong and report it as a fatal error using die. An error can be returned for a number of reasons, such as the file specified could not be found, had embedded directives containing illegal syntax that could not be parsed, or generated a runtime error while the template was being processed.

Template configuration options

We mentioned the --pre_process and --post_process options when using ttree earlier. Now we can see how these are used in the underlying Perl implementation.

Configuration options are passed to the new( ) constructor method as a reference to a hash, as shown in Example 1-7. The Template module expects options to be provided in uppercase, so the options for ttree translate to the PRE_PROCESS and POST_ PROCESS options for the Template module. We also set the INCLUDE_PATH option to indicate the location of the source and library templates, which ttree provides from the src (or -s) and lib (or -l) options. These are provided as a reference to a list of the two directory paths.

my $tt = Template->new({
      PRE_PROCESS => 'header',
      POST_PROCESS => 'footer',
      INCLUDE_PATH => [
            '/home/dent/web/templates',  # src
            '/home/dent/web/lib',        # lib
      ],
});

Example 1-7. Specifying options when processing templates, ttperl3.pl

Now when the process( ) method is invoked against the $tt object, the source template, destruction.tt, will be processed complete with the header and footer added before and after the main page content, respectively. For this example, we are assuming that the destruction.tt template is located in the /home/dent/web/templates directory, and that header and footer can be found in the /home/dent/web/lib directory.

The Template Toolkit provides numerous configuration options. These are described in detail in the Appendix. We describe the useful ones as we encounter them in later chapters.

Apache::Template Module

The Apache::Template module marries the Template Toolkit with the Apache web server. It is distributed separately from the rest of the Template Toolkit and can be downloaded at http://search.cpan.org/dist/Apache-Template/. It requires an Apache installation that includes Doug MacEachernís mod_perl extension module, details of which can be found at http://perl.apache.org/. For a full discussion of mod_perl,we recommend Practical mod_perl, by Stas Bekman and Eric Cholet (OíReilly), which contains an appendix dealing specifically with using the Template Toolkit under Apache and mod_perl.

Apache::Template can be configured via Apacheís normal httpd.conf configuration file. Example 1-8 shows an extract of an httpd.conf file that sets the same options as Example 1-7.

PerlModule             Apache::Template

TT2IncludePath         /home/dent/web/templates
TT2IncludePath         /home/dent/web/lib
TT2PreProcess          header
TT2PostProcess         footer

TT2Params              uri env params cookies
TT2Headers             modified length

<Files *.tt2> 
    SetHandler         perl-script 
    PerlHandler        Apache::Template
</Files>

Example 1-8. httpd.conf directives to set options with Apache::Template

The first section loads the Apache::Template module: PerlModule Apache::Template

PerlModule             Apache::Template

The next block sets some standard Template Toolkit options:

TT2IncludePath         /home/dent/web/templates
TT2IncludePath         /home/dent/web/lib
TT2PreProcess          header
TT2PostProcess         footer

Apache::Template adopts the Apache convention of using StudlyCaps for the names of configuration options and also adds a unique TT2 prefix. So the Apache::Template options TT2IncludePath and TT2PreProcess, for example, equate to the INCLUDE_PATH and PRE_PROCESS options for the Template module.

The two options that follow are specific to the Apache::Template handler:

TT2Params         uri env params cookies
TT2Headers        modified length

The first, TT2Params, provides a list of items that the handler should automatically extract from the Apache request and make available as template variables. Any template can use the uri, env, params, and cookies variables to access the request URI, environment variables, request parameters, and cookies, respectively. The second directive, TT2Headers, indicates that Last-Modified and Content-Length headers should be automatically added to the response sent to the client.

The final section uses the Apache Files directive to define the files that should be processed as templates:

<Files *.tt2>
    SetHandler perl-script
    PerlHandler Apache::Template
</Files>

The SetHandler and PerlHandler directives within the Files block are standard procedure in Apache for binding a mod_perl handler (Apache::Template in this case) to a set of files. With this configuration, the Apache server processes any files with a .tt2 extension using the Apache::Template handler, but continues to deliver pages with any other extensions as static files, or using any other handlers defined for them.

This is a convenient way of mixing static HTML pages with dynamic page templates in any directory that is currently accessible by the Apache web server. If you want to create a static page, use a .html or other appropriate extension. If you want to create a dynamic page from a template, with the appropriate headers and footer added automatically, simply give it a .tt2 extension and leave Apache::Template to take care of it.

If you would rather not open up your entire web server to the Apache::Template module, you can instead use the Location directive.

<Location /tt2/>
SetHandler              perl-script
PerlHandler             Apache::Template
</Location>

In this case, only those files located under the /tt2/ URI will be processed through the Apache::Template handler.

There are numerous other Apache configuration directives, all of which are described in the documentation provided with Apache. For a full discussion of the Apache:: Template configuration, see the Appendix.  

Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

Visit the O'Reilly Network http://www.oreillynet.com for more online content.



 
 
>>> More Perl Programming Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: