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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Getting Started with the Perl Template Toolkit - Template Processing Directives
    (Page 9 of 10 )

    Another use of template directives is for changing the way templates are processed. The PROCESS directive is one of the simplest. It loads another template file, processes the contents, and inserts the generated output in the calling template:

    [% PROCESS header %]

    The Template Toolkit provides the INCLUDE_PATH option, which allows you to specify one or more directories where your template files can be found. This allows you to specify your templates with simple names such header, rather than full file paths such as /home/dent/templates/lib/header, for example.

    The reason that it is called INCLUDE_PATH and not PROCESS_PATH becomes obvious when we mention that there is also an INCLUDE directive. The INCLUDE directive and related INCLUDE_PATH option have been part of the Template Toolkit, and the Text:: Metatext module that preceded it, from the very beginning. The PROCESS directive, on the other hand, was added at a later date, and was able to reuse the INCLUDE_PATH option for the same purposes.

    The difference between PROCESS and INCLUDE is revealed in Chapter 2. For now it suffices to know that INCLUDE is most often used when you want to pass variable values that should remain local to that one template:

    [% INCLUDE header
          title = 'Vogon Poetry'
    %]

    The Template Toolkit is quite relaxed about how you lay out directives. You can add as little or as much whitespace as you like (including newlines) to help make your directive more readable. The only rule is that you must separate individual words and phrases in the directive (e.g., the INCLUDE keyword and the header template name that follows it) with at least one whitespace character. You don’t need any spacing between the opening tag and the start of the directive, or between the end of the directive and the closing tag, but we recommend it to help make directives easier to read.

    The following examples are all valid and equivalent ways of writing the same directive:

    [%INCLUDE header title='Vogon Poetry'%]

    [% INCLUDE header title='Vogon Poetry' %]

    [% INCLUDE header
             title = 'Vogon Poetry'
    %]

    Loops

    The FOREACH directive allows you to create loops, where a block of template content is processed, once for each item in a list. Here’s the general form:

    [% FOREACH item IN list %]
       block of template content...
       ...can contain directives...
       ...and reference the [% item %] variable...
    [% END %]

    We’ve already seen a real example of this in action:

    You know the following terms:
    [% FOREACH term IN terms.keys.sort -%]
      [% term %]: [% terms.$term %]
    [% END -%]

    We know from looking at virtual methods earlier that the terms.keys.sort variable returns a list of the items frood, hoopy, and sass. So our loop block will be repeated three times, with the term variable set to each of those values in turn. We print the term followed by its definition, fetched from the terms hash array using the value of term as the key. The term variable must be prefixed with $ to indicate that the value of the variable should be used rather than the literal string term:

    [% term %]: [% terms.$term %]

    The output generated for the complete block is as follows:

    You know the following terms:
      frood: really, amazingly together guy
      hoopy: really together guy
      sass: know, be aware of, meet, have sex with

    Conditionals

    Conditionals are another powerful language feature that allow your templates to make decisions about what to process and what not to process, based on the values of variables and more complex expressions.

    We saw an example of the IF directive in Example 1-3, shown here in condensed form for brevity:

    [% IF order.destruction %]
       As you will no doubt be aware...
    [% ELSE %] 
       Our representatives will be...
    [% END %]

    If the order.destruction variable is true, the first block, between the IF and ELSE directives, is processed. Otherwise, the block between the ELSE and END is used.

    The notion of truth is, in this sense, the same as it is for Perl. If the variable is defined and contains any kind of value except an empty string or the number zero, both Perl and the Template Toolkit will consider it to be true. If the variable is undefined, or contains a zero-length string or the number zero, it is false. This applies to all Template Toolkit directives that perform operations based on evaluating a variable or more complex expressions for truth.

    Filters, Plugins, and Macros

    There’s plenty more in the Template Toolkit that we introduce in the chapters that follow. The following examples give a taste of what is to come.

    Filters allow you to postprocess the output of a block of template markup. The html filter, for example, will convert any HTML-sensitive characters, such as <, >, and &, into their equivalent HTML entities, <, >, and &.

    [% FILTER html %]
       Home > Dent > Friends > Slartibartfast
    [% END %]

    This generates the following output, which, when displayed as HTML on a web browser, will show the original > characters as intended:

    Home > Dent > Friends > Slartibartfast

    See Chapter 5 for further details.

    Plugins allow you to load and use Perl modules in templates without having to write a Perl wrapper program to do it for you. The following examples show how the CGI plugin (which delegates to Lincoln Stein’s CGI.pm module) can be used for CGI programming:

    [% USE CGI %]
    [% name = CGI.param('name') or 'Arthur Dent' %]
    [% planet = CGI.param('planet') or 'Earth' %]
     Welcome [% name %] of planet [% planet %].

    Plugins also have their own chapter, Chapter 6.

    The final teaser that we’re going to show you is the MACRO directive. This allows you to provide simple names for more complex commands, as the following example shows:

    [% MACRO header(title, author)
         IF name == 'Arthur Dent';
            INCLUDE arthur/header
              title = "Arthur Dent: $title";
         ELSE;
            INCLUDE guest/header
              title = "Guest User: $title";
         END;
    %]

    Don’t worry if you can’t make much sense of that now. The point that we’re illustrating is that sometimes Template Toolkit code can get quite complex. However, the MACRO directive allows you to define the complicated part in one place so that you can use a much simpler call to the macro in the rest of your templates:

    [% header('Arthur Dent', 'My Home Page') %]

     

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