Perl
  Home arrow Perl arrow Page 6 - Getting Started with the Perl Template...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PERL

Getting Started with the Perl Template Toolkit
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 20
    2004-07-28

    Table of Contents:
  • Getting Started with the Perl Template Toolkit
  • The Templating Ecosystem
  • Installing the Template Toolkit
  • Documentation and Support
  • Using the Template Toolkit
  • The Template Module
  • The Template Toolkit Language
  • Dynamic Variables
  • Template Processing Directives
  • Integrating and Extending the Template Toolkit

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    PCmover - $15 Off with Coupon Code CJPH7Q

    Getting Started with the Perl Template Toolkit - The Template Module
    (Page 6 of 10 )

    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 Articles
    More By O'Reilly Media


     

       

    PERL ARTICLES

    - Perl: A Continuing Look at Hashes and Multid...
    - Perl: Another Round with Hashes
    - Perl Hashes
    - Perl Lists: A Final Look at List::Util
    - Perl Lists: Utilizing List::Util
    - Perl Lists: The Split() Function
    - SQL and CGI with Perl and DBI
    - Perl Lists: More Functions and Operators
    - SELECT Queries and Perl
    - Perl Lists: More on Manipulation
    - Creating a Database with Perl and DBI
    - Perl: Sailing the List(less) Seas
    - Perl and DBI
    - Perl: Concatenating Text and More
    - Perl Text: Quoting Without Quote Marks

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway