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

    PCmover - $15 Off with Coupon Code CJPH7Q

    Getting Started with the Perl Template Toolkit - Dynamic Variables
    (Page 8 of 10 )

    The examples that we’ve seen so far have used variables to store static values. When you set a variable to contain a scalar value or a reference to a list or hash array, it remains set to that value until the next time you explicitly modify it. Whenever the variable is used, the Template Toolkit simply looks up the current value for the variable and inserts it in the right place.

    The Template Toolkit also allows subroutines and objects to be used to create dynamic variables. Each time such a variable is used, the Template Toolkit will call the subroutine or object method bound to it to return an appropriate value. Whereas static variables contain precomputed values, these dynamic variables return values that are recomputed each time they are used.

    Example 1-11 shows a Perl program that defines two template variables, one bound to a subroutine, the other to an object.

    use Acme::Planet;       # not a real module (yet)

    my $vars = { 
        help => sub {
            my $entry = shift;
            return "$entry: mostly harmless";
        },
        planet => Acme::Planet->new( name => 'Earth' ),
    };

    Example 1-11. Dynamic data in template variables

    In this example, the help variable is a reference to a subroutine that expects a single argument, $entry. The planet variable references a hypothetical Acme::Planet object. This isn’t a real module (at the time of this writing), but we’re assuming that the new constructor method creates an Acme::Planet object against which we can invoke the name( ) method to return the value provided, Earth.

    The following extract shows how these variables can be used in a template:

    The guide has this to say about [% planet.name %].
    [% help(planet.name) %]

    This would generate the following output:

    The guide has this to say about Earth.
      Earth: mostly harmless

    Notice that when we call the name method on planet we use the dot operator in exactly the same way as we would if planet were a hash with a key called name. The Template Toolkit doesn’t care which of these we have, it just looks at the variable and works out what is the right thing to do. This illustrates how you are not tied down to any particular implementation for your underlying data structures, and can freely change from hashes to objects and back again without affecting the templates that use them.

    Dynamic variables must be defined in Perl. There is no easy or clean way to define dynamic variables from within a template, other than by enabling the EVAL_PERL configuration option and using embedded Perl. The preferred solution is to write a simple Perl script that defines the relevant subroutines, objects, and other data items and then processes the appropriate template or templates. Another approach is to write a Template Toolkit plugin that encapsulates the Perl code and can be loaded into any template on demand. We look at plugins in detail in Chapter 6.

    Virtual Methods

    The Template Toolkit provides virtual methods for manipulating and accessing information about template variables. For example, the length virtual method can be applied to any scalar variable to return its string length in characters. The virtual method is applied using the dot operator:

    [% name = 'Slartibartfast' %]
    [%name%]'s name is [% name.length %] characters long.

    This generates the output:

    Slartibartfast's name is 14 characters long.

    Virtual methods are provided for the three main variables types: scalars, lists, and hashes. The following example shows the join list virtual method being used to return the elements in a list joined into a single string. It adds a single space character between each item in the list by default, but you can provide a different delimiter by passing it as an argument in parentheses.

    [% friends = [ 'Andy', 'Darren', 'Dave'] %]
    Your friends are [% friends.join(', ') %].

    This will display:

    Your friends are Andy, Darren, Dave.

    Some virtual methods alter the contents of the variable that they act on. For example, the pop method removes the last item from a list and returns it:

    [% last = friends.pop %]
    Your friends are [%friends.join(', ')%] and [%last%].

    This will display:

    Your friends are Andy, Darren and Dave.

    We saw an example earlier of how virtual methods were combined in a dotted variable:

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

    The part that we’re particularly interested in is this:

    terms.keys.sort

    The terms variable contains a reference to a hash. The keys hash virtual method returns a reference to a list of the keys in the hash. The keys aren’t returned in any particular order, but now that we have a list, we can go on to call the sort list virtual method to return a second list containing the items sorted in alphabetical order.

    We can then go one step further and call the join virtual method on that list, to join the items into a single string:

    [% terms.keys.sort.join(', ') %]

    This generates the following output:

    frood, hoopy, sass

    Virtual methods are covered in detail in Chapter 3.

    Template Directives

    The examples we have looked at so far have concentrated on the use of variables. The Template Toolkit also provides more advanced language constructs called direc tives. These begin with an uppercase keyword such as PROCESS, IF,or FOREACH and tell the template processing engine to do something.

    Variable Directives

    Given that directives start with an uppercase keyword, you might be forgiven for thinking that the examples we have seen so far don’t count as directives:

    [% name = 'Arthur Dent' %]
    [% planet = { name = 'Earth' } %]
    Welcome [% name %] of [% planet.name %].

    However, the syntax that we have been using until now to set and get variables is actually just a convenient shortcut for the full version, which uses the SET and GET keywords like so:

    [% SET name = 'Arthur Dent' %]
    [% SET planet = { name = 'Earth' } %]
    Welcome [% GET name %] of [% GET planet.name %].

    For obvious reasons, the shorter versions are used most of the time. 

    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