Perl
  Home arrow Perl arrow Page 5 - 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 
 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

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    Getting Started with the Perl Template Toolkit - Using the Template Toolkit
    (Page 5 of 10 )

    The rest of this chapter provides a brief introduction to using the Template Toolkit. We look at the structure and syntax of templates, showing how variables and directives are embedded in plain text and expanded by the template processing engine. We talk about some of the different kinds of directives that the Template Toolkit provides, what they’re used for, and how you go about using them.

    We start by looking at the four main ways of using the Template Toolkit to process templates: from the command line using the tpage and ttree programs; from a Perl script using the Template module; and in a mod_perl-enabled Apache web server using the Apache::Template module.

    tpage

    The tpage program provides a quick and easy way to process a template file from the command line. The name of the template file is specified as a command-line argument. This is processed through the Template Toolkit processing engine, and the resultant output is printed to STDOUT:

    $ tpage infile

    You can use the > file redirect operator (if your operating system supports it, or something similar) to save the output into another file:

    $ tpage infile > outfile

    In this example, the input template, infile, is processed by tpage with the output saved in outfile. If something goes wrong and the template can’t be processed (for example, if the input file specified doesn’t exist or contains an invalid template directive or markup error), an error is printed to STDERR, and tpage exits without generating any standard output.

    The following shows what happens if we try and coerce tpage into processing a file, nosuchfile, which doesn’t exist on our system:

    $ tpage nosuchfile
    file error - nosuchfile: not found at /usr/bin/tpage line 60.

    tpage offers just one command-line option, --define, which allows you to provide values for template variables embedded in the document. We saw this earlier in Example 1-1 where it processed the Vogon form letter:

    $ tpage --define planet=Earth \
    >         --define captain="Prostetnic Vogon Jeltz" \
    >         --define time="two of your earth minutes" \
    >         destruction.tt

    The tpage program is ideal for simple template processing such as this, where nothing more is required than the ability to insert a few variable values. More complex tasks need the ttree program or custom programs using the Template module.

    However, there is one last tpage trick we can show you. If you don’t provide tpage with the name of a template file, it reads it from STDIN. This allows you to use it as Unix-style pipeline filter. For example, if the output of the mktemplate program is a Template Toolkit template, the following command can be used to pipe it into tpage to have it processed:

    $ mktemplate | tpage

    Invoking tpage by itself, with no arguments and no piped input, starts it in interactive mode. In this case, tpage sits and waits for you to type in a source template. This can be very useful for trying out small snippets of template syntax to see what they do.

    Here’s an example:

    $ tpage
    [% subject = 'cat'
         object = 'mat'
    %]
    The [% subject %] sat on the [% object %].
    ^D
    The cat sat on the mat.

    The first line invokes tpage from the command line. The next three lines are the body of the template in which we type, followed by the end-of-file (EOF) character telling tpage that we’re done. On Unix systems, this is Ctrl-D, shown in the example as ^D. On Microsoft Windows platforms, Ctrl-Z is the EOF character.

    The rest of the example shows the output generated by tpage from processing the template. The cat is sitting on the mat, and everything is working as expected.

    ttree

    The ttree program offers many more features and options than tpage does. The first major difference is that ttree works with entire directories of templates rather than with single files. If you’re using the Template Toolkit to build a web site, for example, you can point ttree at a directory of source templates to process them all, saving the generated HTML pages to corresponding files in an output directory.

    The following example shows how you could invoke ttree to process all the templates in the templates directory (containing the files cat and dog for the purpose of this example), and save the generated output in files of the same name, which are located in the output directory:

    $ ttree -s templates -d output -v

    The -s option defines the source directory for templates, and -d defines the destination directory for output files. The -v (verbose) option causes ttree to print a sum mary of what it’s doing to STDERR.

    Here’s an example of the kind of information generated by the -v option:

    ttree 2.63 (Template Toolkit version 2.10)

          Source:   templates
     Destination:   output
    Include Path:   [  ] 
          Ignore:   [  ] 
            Copy:   [  ] 
          Accept:   [*]

    + dog
    + cat

    This is a summary of the processing options, including the Source and Destination that we provided as the -s and -d command-line options. The dog and cat files are listed as the two files that ttree found in the templates directory. The + characters indicate that both files were successfully processed, creating dog and cat files in the output directory.

    Now that these templates have been processed, ttree will not process them again until they are modified or the corresponding output file is deleted. By looking at the file modification times of the source template and destination file, ttree can decide which templates have changed and which have not. It saves time by processing only those that have changed.

    If you run the same ttree command again, you see that the + characters to the left of the filenames have changed to -characters:

    ttree 2.63 (Template Toolkit version 2.10)

          Source:   templates
     Destination:   output
    Include Path:   [  ] 
          Ignore:   [  ] 
            Copy:   [  ] 
          Accept:   [*]

    + dog                   (not modified)
    + cat                   (not modified)

    These -characters indicate that the template files were not processed this time, with the reason given in parentheses to the right. This can save a great deal of time when

    building large document systems using templates (e.g., a typical web site) in which only a few pages change at any one time.

    The -a option forces ttree to process all templates, regardless of their modification times:

    $ ttree -a

    A second benefit of ttree is that it offers numerous options for changing its behavior. Adding a standard header and footer to each page template, for example, is as easy as setting the relevant option:

    $ ttree -s templates -d output -v \
    > --pre_process=header \
    > --post_process=footer

    The number of options can be overwhelming at first, but in practice, only a few are used on a regular basis. To avoid having to always use the command line to specify options—something that can quickly become cumbersome and error prone, especially if you are using more than a few— ttree allows you to use configuration files to

    define all the options for a particular web site or other document system. You can then invoke ttree, passing the name of the configuration file using the -f option:

    $ ttree -f /home/dent/web/ttree.cfg

    src = /home/dent/web/templates
    dest = /home/dent/web/html
    lib = /home/dent/web/lib

    pre_process = header
    post_process = footer

    verbose

    Example 1-5. A sample ttree configuration file, ttree.cfg

    In the configuration file, the -s and -d options are represented by the src and dest options. We also added a lib option (-l on the command line), which tells ttree about an additional library directory where our header and footer templates are found.

    Setting up ttree is a little more involved than using tpage, but the effort quickly pays off in the time it saves you. We look at ttree in detail in Chapter 2, showing everything from first-time use through writing and managing configuration files.  

    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 4 hosted by Hostway